diff --git a/src/GameCult.Caching/CultCache.cs b/src/GameCult.Caching/CultCache.cs index b7945177..e94f6ac3 100644 --- a/src/GameCult.Caching/CultCache.cs +++ b/src/GameCult.Caching/CultCache.cs @@ -4235,8 +4235,7 @@ namespace GameCult.Caching { if (record == null) throw new ArgumentNullException(nameof(record)); if (catalogEntry == null) throw new ArgumentNullException(nameof(catalogEntry)); - if (Cache != null) - throw new InvalidOperationException("The store is attached to a cache, write through the cache."); + RefuseWhenAttached(); if (registry != null) AttachRegistry(registry); Held(() => @@ -4246,6 +4245,79 @@ namespace GameCult.Caching }); } + /// + /// Writes one typed document to the store file without a cache, as a cache write would. Element ids are decided before anything + /// is written: an unset id is minted, a list a cache write refuses refuses the write, and the file is marked as holding element + /// ids when the document holds one. A write that fails gives the minted ids back. Then the document is encoded with + /// and stored as stores a record: every other record and catalog entry + /// is copied forward as stored, under the store's lock, and the file is replaced atomically. + /// + /// The registered document type. + /// The record key the document is stored under. + /// The document to store. + /// The stored-at stamp, or null for now. + /// The registry that describes and encodes the document, or null for . + /// The store is attached to a cache; write through the cache. + /// The file at the path is not a store this runtime can read. + /// The document holds an element id or list a cache write refuses. + public void WriteDocument(CultRecordKey key, TDocument document, string? storedAt = null, CultDocumentRegistry? registry = null) + where TDocument : class + { + if (document == null) throw new ArgumentNullException(nameof(document)); + RefuseWhenAttached(); + var resolvedRegistry = registry ?? CultDocumentRegistry.Shared; + var catalogEntry = resolvedRegistry.GetRequired().ToCatalogEntry(); + AttachRegistry(resolvedRegistry); + var ids = CultElementIds.Plan(typeof(TDocument), document, key.Value, deterministic: false); + ids.Apply(); + try + { + WriteRecord( + new CultPersistedRecord + { + Key = key.Value, + SchemaId = catalogEntry.SchemaId, + StoredAt = string.IsNullOrWhiteSpace(storedAt) ? DateTimeOffset.UtcNow.ToString("O") : storedAt!, + Payload = SerializePayload(document) + }, + catalogEntry, + CultElementIds.Holds(typeof(TDocument), document)); + } + catch + { + ids.Undo(); + throw; + } + } + + /// + /// Decodes a document payload read from this store file, as a cache load decodes it: the ids a load mints are minted from the key + /// and their path, so every reader of one store mints the same ids, and a payload a cache write would refuse is refused here too. + /// + /// The registered document type. + /// The record key the payload was stored under. + /// The record's payload. + /// The registry that describes and decodes the document, or null for . + /// The store is attached to a cache; read through the cache. + /// The payload holds an element id or list a cache load refuses. + public TDocument DecodeDocument(CultRecordKey key, byte[] payload, CultDocumentRegistry? registry = null) + where TDocument : class + { + if (payload == null) throw new ArgumentNullException(nameof(payload)); + if (Cache != null) + throw new InvalidOperationException("The store is attached to a cache, read through the cache."); + AttachRegistry(registry ?? CultDocumentRegistry.Shared); + var document = (TDocument)DeserializePayload(typeof(TDocument), payload); + CultElementIds.Plan(typeof(TDocument), document, key.Value, deterministic: true).Apply(); + return document; + } + + private void RefuseWhenAttached() + { + if (Cache != null) + throw new InvalidOperationException("The store is attached to a cache, write through the cache."); + } + // Flush, commit and Mesh's write all end here, with the durable store they read under the lock they hold. First, a key the write // names or checks whose durable record is under an id the writer does not declare refuses the write (RefuseUndeclaredOnDisk); a // write that then has nothing to write but keys it checked writes no file. Then a store that holds diff --git a/src/GameCult.Caching/CultElementIds.cs b/src/GameCult.Caching/CultElementIds.cs index 7088be09..38dfaaae 100644 --- a/src/GameCult.Caching/CultElementIds.cs +++ b/src/GameCult.Caching/CultElementIds.cs @@ -53,12 +53,12 @@ namespace GameCult.Caching // non-empty. Either need only be unique within one list. A write mints a random id; a load of a store written before ids // existed mints from SHA-256(record key, element path), so every reader of the same store mints the same id and a reload is // identical to what was read. A write and a load refuse the same things. - public static class CultElementIds + internal static class CultElementIds { private const int IdBytes = 6; /// The element ids a pass would fill, decided before anything changes. sets them; gives back what Apply replaced. - public sealed class IdPlan + internal sealed class IdPlan { private readonly List<(object Item, Shape Shape, string? Before, string Id)> _fills = new(); diff --git a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs index 0d1dd4b4..39a087ba 100644 --- a/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs +++ b/src/GameCult.Mesh/CultMeshSingleFileDocuments.cs @@ -94,28 +94,9 @@ namespace GameCult.Mesh { if (document == null) throw new ArgumentNullException(nameof(document)); - var resolvedRegistry = registry ?? CultDocumentRegistry.Shared; - var descriptor = resolvedRegistry.GetRequired(); - // Element ids are decided as a cache write decides them, before anything is written: an unset id is minted, a - // refused list refuses the write, and the file is marked when it holds an id. A failed write gives the ids back. - var ids = CultElementIds.Plan(typeof(TDocument), document, key.Value, deterministic: false); - ids.Apply(); - try - { - WriteSingleFileDocumentPayload( - path, - key, - descriptor.ToCatalogEntry(), - storedAt, - CultDocumentMessagePackSerialization.SerializeUntyped(document, typeof(TDocument)), - CultElementIds.Holds(typeof(TDocument), document), - resolvedRegistry); - } - catch - { - ids.Undo(); - throw; - } + if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Value must be non-empty.", nameof(path)); + // The store decides element ids, the header and the copy of every other record, as a cache write does. + StoreAt(path).WriteDocument(key, document, storedAt, registry); } /// @@ -130,10 +111,8 @@ namespace GameCult.Mesh var resolvedRegistry = registry ?? CultDocumentRegistry.Shared; var descriptor = resolvedRegistry.GetRequired(); var payload = ReadSingleFileDocumentPayload(path, key, descriptor.SchemaId); - var document = (TDocument)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(TDocument), payload); // A load refuses what a write refuses, and mints the ids a cache load of the same file would mint. - CultElementIds.Plan(typeof(TDocument), document, key.Value, deterministic: true).Apply(); - return document; + return StoreAt(path).DecodeDocument(key, payload, resolvedRegistry); } /// diff --git a/tests/GameCult.Caching.ConsumerBuild/Program.cs b/tests/GameCult.Caching.ConsumerBuild/Program.cs index 1405cfd3..3280b35f 100644 --- a/tests/GameCult.Caching.ConsumerBuild/Program.cs +++ b/tests/GameCult.Caching.ConsumerBuild/Program.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Linq; using GameCult.Caching; using MessagePack; @@ -17,8 +18,8 @@ var committed = outside.Commit(batch => if (!committed) return 1; -// A store file is written and read without a cache through the two public members: this project has no InternalsVisibleTo, so -// building it pins that ReadStoreSnapshot and WriteRecord are public API. +// A store file is written and read without a cache through the public members: this project has no InternalsVisibleTo, so +// building it pins that ReadStoreSnapshot, WriteRecord, WriteDocument and DecodeDocument are public API. var storePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "consumer-build-" + System.Guid.NewGuid().ToString("N") + ".cc"); try { @@ -28,6 +29,11 @@ try var snapshot = store.ReadStoreSnapshot(); if (snapshot == null || snapshot.Records.Length != 1 || snapshot.Records[0].Key != "r") return 1; + var typedRegistry = CultDocumentRegistry.ForTypes(new[] { typeof(ConsumerFaction) }); + store.WriteDocument(new CultRecordKey("f"), new ConsumerFaction { Name = "typed" }, registry: typedRegistry); + var typed = store.ReadStoreSnapshot()!.Records.Single(record => record.Key == "f"); + if (store.DecodeDocument(new CultRecordKey("f"), typed.Payload, typedRegistry).Name != "typed") + return 1; } finally { diff --git a/tests/GameCult.Caching.Tests/CachelessSingleFileTests.cs b/tests/GameCult.Caching.Tests/CachelessSingleFileTests.cs index a1d0125e..6c5fc5d3 100644 --- a/tests/GameCult.Caching.Tests/CachelessSingleFileTests.cs +++ b/tests/GameCult.Caching.Tests/CachelessSingleFileTests.cs @@ -1,6 +1,7 @@ #nullable enable using System; using System.IO; +using System.Linq; using System.Threading.Tasks; using GameCult.Caching.MessagePack; using NUnit.Framework; @@ -8,8 +9,8 @@ using static GameCult.Caching.Tests.ElementIdTests; namespace GameCult.Caching.Tests { - // A single-file store file is read and written without a cache through ReadStoreSnapshot and WriteRecord: the same reader, lock, - // atomic replace and header rule a cache's store uses. CultMesh's single-file document helpers are built on these two members. + // A single-file store file is read and written without a cache through ReadStoreSnapshot, WriteRecord, WriteDocument and DecodeDocument: the same reader, lock, + // atomic replace and header rule a cache's store uses. CultMesh's single-file document helpers are built on these members. public class CachelessSingleFileTests { private static readonly CultSchemaCatalogEntry One = new() { SchemaId = "tests.cacheless.one", SchemaName = "tests.cacheless.one" }; @@ -148,5 +149,48 @@ namespace GameCult.Caching.Tests Assert.That(new SingleFileMessagePackBackingStore(_path).ReadStoreSnapshot()!.FormatVersion, Is.EqualTo(expected)); } + + [Test] + public void WriteDocumentMintsIdsMarksV3AndKeepsTheOtherRecord() + { + var registry = CultDocumentRegistry.ForTypes(new[] { typeof(IdDeck) }); + new SingleFileMessagePackBackingStore(_path).WriteRecord(Record("other", One, 1), One); + var deck = new IdDeck { Name = "deck", Reels = { new IdReel { Label = "reel" } } }; + + new SingleFileMessagePackBackingStore(_path).WriteDocument(new CultRecordKey("deck"), deck, registry: registry); + + var snapshot = new SingleFileMessagePackBackingStore(_path).ReadStoreSnapshot()!; + Assert.That(snapshot.FormatVersion, Is.EqualTo(CultPersistedStoreSnapshot.FormatV3)); + Assert.That(snapshot.Records.Select(record => record.Key), Is.EquivalentTo(new[] { "other", "deck" })); + Assert.That(deck.Reels[0].Id, Does.Match("^[0-9a-f]{12}$"), "the id the file holds was minted on the document"); + var read = new SingleFileMessagePackBackingStore(_path).DecodeDocument(new CultRecordKey("deck"), snapshot.Records.Single(record => record.Key == "deck").Payload, registry); + Assert.That(read.Reels[0].Id, Is.EqualTo(deck.Reels[0].Id)); + } + + [Test] + public void WriteDocumentGivesMintedIdsBackWhenTheWriteIsRefused() + { + var registry = CultDocumentRegistry.ForTypes(new[] { typeof(IdDeck) }); + File.WriteAllBytes(_path, new byte[] { 0xC1 }); + var deck = new IdDeck { Name = "deck", Reels = { new IdReel { Label = "reel" } } }; + + Assert.Throws(() => + new SingleFileMessagePackBackingStore(_path).WriteDocument(new CultRecordKey("deck"), deck, registry: registry)); + + Assert.That(deck.Reels[0].Id, Is.Null.Or.Empty, "a refused write leaves the document as it was"); + } + + [Test] + public void WriteDocumentAndDecodeDocumentRefuseOnAStoreAttachedToACache() + { + var registry = CultDocumentRegistry.ForTypes(new[] { typeof(IdDeck) }); + var store = new SingleFileMessagePackBackingStore(_path); + using var cache = new CultCache(registry); + cache.AddBackingStore(store); + + Assert.That(Assert.Throws(() => store.WriteDocument(new CultRecordKey("deck"), new IdDeck { Name = "d" }))!.Message, Does.Contain("write through the cache")); + Assert.That(Assert.Throws(() => store.DecodeDocument(new CultRecordKey("deck"), new byte[] { 0x90 }))!.Message, Does.Contain("read through the cache")); + Assert.That(File.Exists(_path), Is.False); + } } }