Rewrite CultCache as attribute-first storage

This commit is contained in:
Meta Vens 2026-05-08 01:13:15 +01:00
commit da94389ee2
29 changed files with 1496 additions and 2488 deletions

View file

@ -1,95 +0,0 @@
using System;
using System.Reflection;
namespace GameCult.Caching.MessagePack;
/// <summary>
/// Represents a canonical CultCache payload envelope for cross-runtime exchange.
/// </summary>
public sealed class CultCacheEnvelope
{
/// <summary>
/// Gets or sets the logical document key for the serialized entry.
/// </summary>
public string Key { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the shared document type identifier for the serialized entry.
/// </summary>
public string Type { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the raw MessagePack payload bytes for the entry.
/// </summary>
public byte[] Payload { get; set; } = Array.Empty<byte>();
/// <summary>
/// Gets or sets the RFC3339 timestamp associated with the serialized payload.
/// </summary>
public string StoredAt { get; set; } = string.Empty;
}
/// <summary>
/// Exposes canonical MessagePack payload helpers for <see cref="DatabaseEntry"/> values.
/// </summary>
public static class CultCacheEnvelopeSerialization
{
/// <summary>
/// Serializes a concrete entry to the canonical MessagePack payload bytes used by CultCache.
/// </summary>
public static byte[] SerializePayload(DatabaseEntry entry)
{
if (entry == null) throw new ArgumentNullException(nameof(entry));
var method = typeof(CultCacheEnvelopeSerialization)
.GetMethod(nameof(SerializeGeneric), BindingFlags.NonPublic | BindingFlags.Static)
?.MakeGenericMethod(entry.GetType())
?? throw new InvalidOperationException("Failed to locate typed CultCache envelope serializer.");
return (byte[])method.Invoke(null, [entry])!;
}
/// <summary>
/// Deserializes canonical MessagePack payload bytes into a concrete entry type.
/// </summary>
public static T DeserializePayload<T>(byte[] payload) where T : DatabaseEntry
{
if (payload == null) throw new ArgumentNullException(nameof(payload));
return DatabaseEntrySerialization.Deserialize<T>(payload);
}
/// <summary>
/// Deserializes canonical MessagePack payload bytes into an abstract <see cref="DatabaseEntry"/>.
/// </summary>
public static DatabaseEntry DeserializePayload(byte[] payload)
{
if (payload == null) throw new ArgumentNullException(nameof(payload));
return DatabaseEntrySerialization.Deserialize<DatabaseEntry>(payload);
}
/// <summary>
/// Creates a full exchange envelope for a concrete entry using the supplied metadata.
/// </summary>
public static CultCacheEnvelope CreateEnvelope(
DatabaseEntry entry,
string key,
string type,
string storedAt)
{
if (entry == null) throw new ArgumentNullException(nameof(entry));
if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Envelope key must be non-empty.", nameof(key));
if (string.IsNullOrWhiteSpace(type)) throw new ArgumentException("Envelope type must be non-empty.", nameof(type));
if (string.IsNullOrWhiteSpace(storedAt)) throw new ArgumentException("Envelope storedAt must be non-empty.", nameof(storedAt));
return new CultCacheEnvelope
{
Key = key,
Type = type,
Payload = SerializePayload(entry),
StoredAt = storedAt
};
}
private static byte[] SerializeGeneric<T>(T entry) where T : DatabaseEntry
{
return DatabaseEntrySerialization.Serialize(entry);
}
}

View file

@ -0,0 +1,146 @@
using System;
using GameCult.Caching;
using MessagePack;
using MessagePack.Formatters;
using MessagePack.Resolvers;
namespace GameCult.Caching.MessagePack;
public sealed class CultRecordRefFormatter<T> : IMessagePackFormatter<CultRecordRef<T>>
{
public void Serialize(ref MessagePackWriter writer, CultRecordRef<T> value, MessagePackSerializerOptions options)
{
options.Resolver.GetFormatterWithVerify<string>().Serialize(ref writer, value.Key.Value, options);
}
public CultRecordRef<T> Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
var key = options.Resolver.GetFormatterWithVerify<string>().Deserialize(ref reader, options) ?? string.Empty;
return new CultRecordRef<T>(new CultRecordKey(key));
}
}
public sealed class CultDocumentResolver : IFormatterResolver
{
public static readonly CultDocumentResolver Instance = new();
private CultDocumentResolver() { }
public IMessagePackFormatter<T>? GetFormatter<T>()
{
var generated = GeneratedCultDocumentResolvers.GetFormatter<T>();
if (generated != null)
{
return generated;
}
var type = typeof(T);
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(CultRecordRef<>))
{
var formatterType = typeof(CultRecordRefFormatter<>).MakeGenericType(type.GetGenericArguments()[0]);
return (IMessagePackFormatter<T>)Activator.CreateInstance(formatterType)!;
}
return null;
}
}
public static class CultDocumentMessagePackSerialization
{
public static readonly MessagePackSerializerOptions Options =
MessagePackSerializerOptions.Standard
.WithResolver(CompositeResolver.Create(
CultDocumentResolver.Instance,
StandardResolver.Instance))
.WithSecurity(MessagePackSecurity.UntrustedData);
public static byte[] Serialize<T>(T value)
{
return MessagePackSerializer.Serialize(value, Options);
}
public static T Deserialize<T>(byte[] payload)
{
return MessagePackSerializer.Deserialize<T>(payload, Options);
}
public static byte[] SerializeUntyped(object value, Type type)
{
return MessagePackSerializer.Serialize(type, value, Options);
}
public static object DeserializeUntyped(Type type, byte[] payload)
{
return MessagePackSerializer.Deserialize(type, payload, Options);
}
}
public static class GeneratedCultDocumentResolvers
{
public static IMessagePackFormatter<T>? GetFormatter<T>() => null;
}
public class SingleFileMessagePackBackingStore : SingleFileBackingStore
{
public SingleFileMessagePackBackingStore(string filePath) : base(filePath)
{
}
protected override byte[] SerializeSnapshot(CultPersistedStoreSnapshot snapshot)
{
return CultDocumentMessagePackSerialization.Serialize(snapshot);
}
protected override CultPersistedStoreSnapshot DeserializeSnapshot(byte[] data)
{
return CultDocumentMessagePackSerialization.Deserialize<CultPersistedStoreSnapshot>(data);
}
protected override byte[] SerializePayload(object document)
{
return CultDocumentMessagePackSerialization.SerializeUntyped(document, document.GetType());
}
protected override object DeserializePayload(Type documentType, byte[] payload)
{
return CultDocumentMessagePackSerialization.DeserializeUntyped(documentType, payload);
}
}
public class MultiFileMessagePackBackingStore : MultiFileBackingStore
{
public MultiFileMessagePackBackingStore(string path) : base(path)
{
}
protected override byte[] SerializeRecord(CultPersistedRecord record)
{
return CultDocumentMessagePackSerialization.Serialize(record);
}
protected override CultPersistedRecord DeserializeRecord(byte[] data)
{
return CultDocumentMessagePackSerialization.Deserialize<CultPersistedRecord>(data);
}
protected override byte[] SerializeCatalog(CultSchemaCatalogEntry[] catalog)
{
return CultDocumentMessagePackSerialization.Serialize(catalog);
}
protected override CultSchemaCatalogEntry[] DeserializeCatalog(byte[] data)
{
return CultDocumentMessagePackSerialization.Deserialize<CultSchemaCatalogEntry[]>(data);
}
protected override byte[] SerializePayload(object document)
{
return CultDocumentMessagePackSerialization.SerializeUntyped(document, document.GetType());
}
protected override object DeserializePayload(Type documentType, byte[] payload)
{
return CultDocumentMessagePackSerialization.DeserializeUntyped(documentType, payload);
}
public override string Extension => "msgpack";
}

View file

@ -1,53 +0,0 @@
using System;
using System.Collections.Concurrent;
using MessagePack;
using MessagePack.Formatters;
namespace GameCult.Caching.MessagePack
{
/// <summary>
/// Resolver that knows how to resolve:<br/>
/// 1. Source-generated singleton formatters for DatabaseEntry subclasses<br/>
/// 2. Generic DatabaseLink&lt;T&gt; formatter
/// </summary>
public sealed class DatabaseEntryResolver : IFormatterResolver
{
/// <summary>
/// Shared singleton instance of the resolver.
/// </summary>
public static readonly DatabaseEntryResolver Instance = new DatabaseEntryResolver();
private readonly ConcurrentDictionary<Type, object> _formatterCache = new();
private DatabaseEntryResolver() { }
/// <summary>
/// Resolves a formatter for a cache entry type or a <see cref="DatabaseLink{T}"/>.
/// </summary>
/// <typeparam name="T">The requested serialized type.</typeparam>
/// <returns>The formatter if one is available; otherwise, <c>null</c>.</returns>
public IMessagePackFormatter<T>? GetFormatter<T>()
{
// 1. Check generated resolver mapping
var fmt = GeneratedDatabaseEntryResolvers.GetFormatter<T>();
if (fmt != null) return fmt;
// 2. Provide generic DatabaseLink<T> formatter
var t = typeof(T);
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(DatabaseLink<>))
{
return (IMessagePackFormatter<T>)_formatterCache.GetOrAdd(
t,
static linkType =>
{
var valueType = linkType.GetGenericArguments()[0];
var formatterType = typeof(DatabaseLinkFormatter<>).MakeGenericType(valueType);
return Activator.CreateInstance(formatterType)!;
});
}
// 3. Nothing found
return null;
}
}
}

View file

@ -1,24 +0,0 @@
using MessagePack;
using MessagePack.Resolvers;
namespace GameCult.Caching.MessagePack;
internal static class DatabaseEntrySerialization
{
public static readonly MessagePackSerializerOptions Options =
MessagePackSerializerOptions.Standard
.WithResolver(CompositeResolver.Create(
DatabaseEntryResolver.Instance,
StandardResolver.Instance))
.WithSecurity(MessagePackSecurity.UntrustedData);
public static byte[] Serialize<T>(T value)
{
return MessagePackSerializer.Serialize(value, Options);
}
public static T Deserialize<T>(byte[] payload)
{
return MessagePackSerializer.Deserialize<T>(payload, Options);
}
}

View file

@ -1,33 +0,0 @@
using System;
using MessagePack;
using MessagePack.Formatters;
namespace GameCult.Caching.MessagePack
{
/// <summary>
/// Serializes <see cref="DatabaseLink{T}"/> values as their linked identifier only.
/// </summary>
/// <typeparam name="T">The target entry type.</typeparam>
public sealed class DatabaseLinkFormatter<T> : IMessagePackFormatter<DatabaseLink<T>?> where T : DatabaseEntry
{
/// <inheritdoc />
public void Serialize(ref MessagePackWriter writer, DatabaseLink<T>? value, MessagePackSerializerOptions options)
{
if (value == null) { writer.WriteNil(); return; }
writer.WriteArrayHeader(1);
var fmt = options.Resolver.GetFormatterWithVerify<Guid>();
fmt.Serialize(ref writer, value.LinkID, options);
}
/// <inheritdoc />
public DatabaseLink<T>? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil()) return null;
var c = reader.ReadArrayHeader();
if (c != 1) throw new MessagePackSerializationException($"Invalid DatabaseLink<{typeof(T).Name}> array length {c}, expected 1");
var id = options.Resolver.GetFormatterWithVerify<Guid>().Deserialize(ref reader, options);
var link = new DatabaseLink<T> { LinkID = id };
return link;
}
}
}

View file

@ -1,12 +0,0 @@
// This stub ensures the project compiles before the source generator runs.
using MessagePack.Formatters;
namespace GameCult.Caching.MessagePack
{
static partial class GeneratedDatabaseEntryResolvers
{
// The generator will emit the real implementation.
public static IMessagePackFormatter<T>? GetFormatter<T>() => null;
}
}

View file

@ -1,54 +0,0 @@
using MessagePack;
namespace GameCult.Caching.MessagePack;
/// <summary>
/// Persists all cache entries to a single MessagePack file.
/// </summary>
public class SingleFileMessagePackBackingStore : SingleFileBackingStore
{
/// <summary>
/// Initializes a single-file MessagePack backing store.
/// </summary>
/// <param name="filePath">The path to the backing file.</param>
public SingleFileMessagePackBackingStore(string filePath) : base(filePath) { }
/// <inheritdoc />
public override byte[] Serialize(DatabaseEntry[] entries)
{
return DatabaseEntrySerialization.Serialize(entries);
}
/// <inheritdoc />
public override DatabaseEntry[] Deserialize(byte[] data)
{
return DatabaseEntrySerialization.Deserialize<DatabaseEntry[]>(data);
}
}
/// <summary>
/// Persists each cache entry to its own MessagePack file.
/// </summary>
public class MultiFileMessagePackBackingStore : MultiFileBackingStore
{
/// <summary>
/// Initializes a multi-file MessagePack backing store rooted at the supplied directory.
/// </summary>
/// <param name="path">The root directory for stored entry files.</param>
public MultiFileMessagePackBackingStore(string path) : base(path) { }
/// <inheritdoc />
public override byte[] Serialize(DatabaseEntry entry)
{
return DatabaseEntrySerialization.Serialize(entry);
}
/// <inheritdoc />
public override DatabaseEntry Deserialize(byte[] data)
{
return DatabaseEntrySerialization.Deserialize<DatabaseEntry>(data);
}
/// <inheritdoc />
public override string Extension => "msgpack";
}

View file

@ -1,39 +1,37 @@
# GameCult.Caching.MessagePack
`GameCult.Caching.MessagePack` provides MessagePack-backed persistence for `GameCult.Caching`.
## Scope
The package focuses on:
- MessagePack storage for `DatabaseEntry` models
- single-file and multi-file store implementations
- support for generated formatters for concrete cache-entry types
- formatter support for `DatabaseLink<T>`
- raw persisted-envelope helpers for exact payload relay
`GameCult.Caching.MessagePack` provides MessagePack persistence for the
attribute-first `GameCult.Caching` stack.
## Included Types
- `SingleFileMessagePackBackingStore`
- `MultiFileMessagePackBackingStore`
- `DatabaseEntryResolver`
- `DatabaseLinkFormatter<T>`
- `CultCacheEnvelope`
- `CultCacheEnvelopeSerialization`
- `CultDocumentMessagePackSerialization`
- `CultDocumentResolver`
- `CultRecordRefFormatter<T>`
## Why The Generator Matters
## What It Does
`DatabaseEntry` is abstract. Concrete subclasses need MessagePack formatters to be serializable without hand-writing formatters for each model.
- stores CultCache snapshots and records in MessagePack
- serializes plain attributed document payloads
- keeps explicit `CultRecordRef<T>` values compact on disk/wire
- preserves the cache/store split where metadata lives outside the domain model
That is the role of:
## Example Model
- `GameCult.Caching.MessagePack.Generator`
- `GameCult.Caching.MessagePack.Analyzers`
```csharp
using GameCult.Caching;
using MessagePack;
In practice:
- this package gives you the stores and resolver support
- the generator package produces the actual concrete formatters
[CultDocument("gamecult.item_data", "gamecult.item_data.v1")]
[MessagePackObject]
public sealed class ItemData
{
[Key(0)] [CultName] public string Name = string.Empty;
[Key(1)] public int Value;
}
```
## Typical Usage
@ -48,94 +46,11 @@ cache.AddBackingStore(store);
await cache.PullAllBackingStoresAsync();
```
## Single-File vs Multi-File
## Notes
### `SingleFileMessagePackBackingStore`
Use this when you want one snapshot file containing all entries.
Use cases:
- compact settings data
- simple local persistence
- write-all-at-once workflows
```csharp
var store = new SingleFileMessagePackBackingStore("cache.msgpack");
cache.AddBackingStore(store);
```
### `MultiFileMessagePackBackingStore`
Use this when you want one file per entry.
Use cases:
- large datasets
- debugging persisted entries individually
- change observation through the multi-file base store
```csharp
var store = new MultiFileMessagePackBackingStore("Data");
cache.AddBackingStore(store, typeof(PlayerData));
```
## `DatabaseLink<T>`
`DatabaseLink<T>` is a lightweight reference type used by the cache layer. The MessagePack formatter serializes only the linked `Guid`, not the fully loaded target object.
That means:
- links stay compact on disk
- linked objects are resolved through the active `CultCache`
- deserialized links depend on `DatabaseLinkBase.Cache` pointing at the active cache
## Example Model
```csharp
using GameCult.Caching;
using MessagePack;
[MessagePackObject]
public class ItemData : DatabaseEntry, INamedEntry
{
[Key(1)] public string Name = string.Empty;
[Key(2)] public int Value;
[IgnoreMember]
public string EntryName
{
get => Name;
set => Name = value;
}
}
```
## Practical Notes
- For polymorphic `DatabaseEntry` serialization, use this package with the generator/analyzer package.
- The backing stores build on the semantics of `CultCache`, including primary-store routing and type-specific store routing.
- `MultiFileMessagePackBackingStore` inherits the rename-safe and atomic-write behavior of the hardened `MultiFileBackingStore` base class.
## Raw Envelope Relay
If a neighboring process already shares the same payload contract and just
needs the exact persisted MessagePack bytes, use `CultCacheEnvelope` and
`CultCacheEnvelopeSerialization`.
That gives you:
- the stable cache key
- the explicit entry/document type
- the exact payload bytes
- the stored-at timestamp
This is the seam the newer CultNet raw document/snapshot lane uses for
bit-compatible neighbors. It keeps the transport from decoding bytes into a
generic sludge object only to re-encode the same thing again five seconds
later.
One important constraint: concrete `DatabaseEntry` subclasses still need real
MessagePack formatters. If a consumer assembly has not generated or registered
formatters for a subtype, supply an explicit payload codec at the integration
boundary instead of assuming the abstract resolver will become psychic.
- Payload bytes are MessagePack. Store metadata and schema catalogs are also
persisted through MessagePack in this package.
- The generator package now targets attributed document types instead of
`DatabaseEntry` subclasses.
- The raw CultNet document lane should treat these payload bytes as already
blessed, not decode and re-encode them for sport.