Caching: SingleFileBackingStore.WriteDocument and DecodeDocument own element-id planning; CultElementIds is internal again
Mesh's typed single-file read and write call the store's typed members instead of planning ids through a public CultElementIds. Builds. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
6463f34203
commit
729754278a
5 changed files with 134 additions and 33 deletions
|
|
@ -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
|
|||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <paramref name="registry"/> and stored as <see cref="WriteRecord"/> 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.
|
||||
/// </summary>
|
||||
/// <typeparam name="TDocument">The registered document type.</typeparam>
|
||||
/// <param name="key">The record key the document is stored under.</param>
|
||||
/// <param name="document">The document to store.</param>
|
||||
/// <param name="storedAt">The stored-at stamp, or null for now.</param>
|
||||
/// <param name="registry">The registry that describes and encodes the document, or null for <see cref="CultDocumentRegistry.Shared"/>.</param>
|
||||
/// <exception cref="InvalidOperationException">The store is attached to a cache; write through the cache.</exception>
|
||||
/// <exception cref="CultStoreUnreadableException">The file at the path is not a store this runtime can read.</exception>
|
||||
/// <exception cref="CultElementIdException">The document holds an element id or list a cache write refuses.</exception>
|
||||
public void WriteDocument<TDocument>(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<TDocument>().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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <typeparam name="TDocument">The registered document type.</typeparam>
|
||||
/// <param name="key">The record key the payload was stored under.</param>
|
||||
/// <param name="payload">The record's payload.</param>
|
||||
/// <param name="registry">The registry that describes and decodes the document, or null for <see cref="CultDocumentRegistry.Shared"/>.</param>
|
||||
/// <exception cref="InvalidOperationException">The store is attached to a cache; read through the cache.</exception>
|
||||
/// <exception cref="CultElementIdException">The payload holds an element id or list a cache load refuses.</exception>
|
||||
public TDocument DecodeDocument<TDocument>(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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>The element ids a pass would fill, decided before anything changes. <see cref="Apply"/> sets them; <see cref="Undo"/> gives back what Apply replaced.</summary>
|
||||
public sealed class IdPlan
|
||||
internal sealed class IdPlan
|
||||
{
|
||||
private readonly List<(object Item, Shape Shape, string? Before, string Id)> _fills = new();
|
||||
|
||||
|
|
|
|||
|
|
@ -94,28 +94,9 @@ namespace GameCult.Mesh
|
|||
{
|
||||
if (document == null) throw new ArgumentNullException(nameof(document));
|
||||
|
||||
var resolvedRegistry = registry ?? CultDocumentRegistry.Shared;
|
||||
var descriptor = resolvedRegistry.GetRequired<TDocument>();
|
||||
// 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -130,10 +111,8 @@ namespace GameCult.Mesh
|
|||
var resolvedRegistry = registry ?? CultDocumentRegistry.Shared;
|
||||
var descriptor = resolvedRegistry.GetRequired<TDocument>();
|
||||
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<TDocument>(key, payload, resolvedRegistry);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -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<ConsumerFaction>(new CultRecordKey("f"), typed.Payload, typedRegistry).Name != "typed")
|
||||
return 1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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<IdDeck>(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<CultStoreUnreadableException>(() =>
|
||||
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<InvalidOperationException>(() => store.WriteDocument(new CultRecordKey("deck"), new IdDeck { Name = "d" }))!.Message, Does.Contain("write through the cache"));
|
||||
Assert.That(Assert.Throws<InvalidOperationException>(() => store.DecodeDocument<IdDeck>(new CultRecordKey("deck"), new byte[] { 0x90 }))!.Message, Does.Contain("read through the cache"));
|
||||
Assert.That(File.Exists(_path), Is.False);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue