From 60a3fa9f8272953d27a13c3ea71ef73aa3f4d129 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 27 Jun 2026 14:43:00 +0100 Subject: [PATCH] Add cache-backed CultMesh document handles --- src/GameCult.Mesh/CultMesh.cs | 246 ++++++++++++++++++ src/GameCult.Mesh/CultMeshPrimitives.cs | 47 +++- src/GameCult.Mesh/docs/public-api.md | 27 +- .../CultMeshStreamingTests.cs | 108 ++++++++ 4 files changed, 417 insertions(+), 11 deletions(-) diff --git a/src/GameCult.Mesh/CultMesh.cs b/src/GameCult.Mesh/CultMesh.cs index b4e93588..cfde04af 100644 --- a/src/GameCult.Mesh/CultMesh.cs +++ b/src/GameCult.Mesh/CultMesh.cs @@ -8,6 +8,7 @@ using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; using GameCult.Networking; +using R3; namespace GameCult.Mesh { @@ -412,6 +413,19 @@ namespace GameCult.Mesh return new CultMeshDocumentHandle(BindLiveFeed(context, feed)); } + /// + /// Binds a mutable typed document live feed to a Verse context. + /// + public static CultMeshDocumentHandle BindDocument( + CultMeshVerseContext context, + CultMeshLiveFeed feed, + Func replace) + where TDocument : class + { + if (replace == null) throw new ArgumentNullException(nameof(replace)); + return new CultMeshDocumentHandle(BindLiveFeed(context, feed), replace); + } + /// /// Binds a typed document live feed to a Verse. /// @@ -424,6 +438,19 @@ namespace GameCult.Mesh return BindDocument(verse.Context, feed); } + /// + /// Binds a mutable typed document live feed to a Verse. + /// + public static CultMeshDocumentHandle BindDocument( + CultMeshVerse verse, + CultMeshLiveFeed feed, + Func replace) + where TDocument : class + { + if (verse == null) throw new ArgumentNullException(nameof(verse)); + return BindDocument(verse.Context, feed, replace); + } + /// /// Binds a typed state pointer to a Verse context. /// @@ -884,6 +911,30 @@ namespace GameCult.Mesh return BindDocument(context, feed); } + /// + /// Creates a mutable typed document handle from snapshot/watch/replace delegates and binds it to a Verse context. + /// + public static CultMeshDocumentHandle Document( + string documentId, + CultMeshVerseContext context, + Func> latest, + Func> watch, + Func replace, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (replace == null) throw new ArgumentNullException(nameof(replace)); + + var feed = LiveFeed( + documentId, + (_parameters, queryContext) => latest(queryContext), + (_parameters, queryContext) => watch(queryContext), + sources, + routeHint); + return BindDocument(context, feed, replace); + } + /// /// Creates a typed document handle from snapshot/watch delegates and binds it to a Verse. /// @@ -900,6 +951,175 @@ namespace GameCult.Mesh return Document(documentId, verse.Context, latest, watch, sources, routeHint); } + /// + /// Creates a mutable typed document handle from snapshot/watch/replace delegates and binds it to a Verse. + /// + public static CultMeshDocumentHandle Document( + string documentId, + CultMeshVerse verse, + Func> latest, + Func> watch, + Func replace, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (verse == null) throw new ArgumentNullException(nameof(verse)); + return Document(documentId, verse.Context, latest, watch, replace, sources, routeHint); + } + + /// + /// Creates a typed document handle directly over one CultCache record. + /// + public static CultMeshDocumentHandle Document( + CultCache cache, + CultRecordKey key, + CultMeshVerseContext context, + string? documentId = null, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (cache == null) throw new ArgumentNullException(nameof(cache)); + if (context == null) throw new ArgumentNullException(nameof(context)); + + var descriptor = cache.Registry.GetRequired(); + var sourceList = sources?.ToArray() + ?? new[] { ProjectionSource(key.Value, descriptor.SchemaId, "CultCache record") }; + var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.InProcess, "CultCache document"); + return Document( + ResolveDocumentId(documentId, key), + context, + _ => Task.FromResult(ReadRequired(cache, key)), + _ => cache.WatchRecord(key) + .Where(change => change.Document != null) + .Select(change => change.Document!), + async value => + { + await cache.UpsertAsync(value, new CultRecordHandle(key)).ConfigureAwait(false); + }, + sourceList, + route); + } + + /// + /// Creates a typed document handle directly over one CultCache record. + /// + public static CultMeshDocumentHandle Document( + CultCache cache, + CultRecordKey key, + CultMeshVerse verse, + string? documentId = null, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (verse == null) throw new ArgumentNullException(nameof(verse)); + return Document(cache, key, verse.Context, documentId, sources, routeHint); + } + + /// + /// Creates a typed document handle directly over one CultCache record with a local Verse context. + /// + public static CultMeshDocumentHandle Document( + CultCache cache, + CultRecordKey key, + string? documentId = null, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + return Document( + cache, + key, + Verse("local", "local", routeHint).Context, + documentId, + sources, + routeHint); + } + + /// + /// Creates a typed document handle directly over one distributed CultNet database record. + /// + public static CultMeshDocumentHandle Document( + CultNetDatabase database, + CultRecordKey key, + CultMeshVerseContext context, + string? documentId = null, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (database == null) throw new ArgumentNullException(nameof(database)); + if (context == null) throw new ArgumentNullException(nameof(context)); + + var descriptor = CultDocumentRegistry.Shared.GetRequired(); + var sourceList = sources?.ToArray() + ?? new[] { ProjectionSource(key.Value, descriptor.SchemaId, "CultNet database record") }; + var route = routeHint ?? new CultMeshRouteHint(CultMeshLocalityKind.Automatic, "CultNet database document"); + return Document( + ResolveDocumentId(documentId, key), + context, + async _ => await ReadRequiredAsync(database, key).ConfigureAwait(false), + _ => database.WatchRecord(key) + .Where(change => change.Document != null) + .Select(change => change.Document!), + async value => + { + await database.PutAsync(key, value).ConfigureAwait(false); + }, + sourceList, + route); + } + + /// + /// Creates a typed document handle directly over one distributed CultNet database record. + /// + public static CultMeshDocumentHandle Document( + CultNetDatabase database, + CultRecordKey key, + CultMeshVerse verse, + string? documentId = null, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (verse == null) throw new ArgumentNullException(nameof(verse)); + return Document(database, key, verse.Context, documentId, sources, routeHint); + } + + /// + /// Creates a typed document handle directly over one CultMesh node database record. + /// + public static CultMeshDocumentHandle Document( + CultMeshNode node, + CultRecordKey key, + CultMeshVerseContext context, + string? documentId = null, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (node == null) throw new ArgumentNullException(nameof(node)); + return Document(node.Database, key, context, documentId, sources, routeHint); + } + + /// + /// Creates a typed document handle directly over one CultMesh node database record. + /// + public static CultMeshDocumentHandle Document( + CultMeshNode node, + CultRecordKey key, + CultMeshVerse verse, + string? documentId = null, + IEnumerable? sources = null, + CultMeshRouteHint? routeHint = null) + where TDocument : class + { + if (verse == null) throw new ArgumentNullException(nameof(verse)); + return Document(node, key, verse.Context, documentId, sources, routeHint); + } + /// /// Describes a typed live feed surface for tooling, UI, and diagnostics. /// @@ -1395,5 +1615,31 @@ namespace GameCult.Mesh return Dns.GetHostAddresses(host).FirstOrDefault() ?? throw new InvalidOperationException($"Could not resolve RUDP host {host}."); } + + private static string ResolveDocumentId(string? documentId, CultRecordKey key) + { + return string.IsNullOrWhiteSpace(documentId) + ? key.Value + : documentId!; + } + + private static TDocument ReadRequired(CultCache cache, CultRecordKey key) + where TDocument : class + { + return cache.Get(key) + ?? throw new KeyNotFoundException( + $"CultMesh document '{key.Value}' was not found as {typeof(TDocument).FullName}."); + } + + private static async Task ReadRequiredAsync( + CultNetDatabase database, + CultRecordKey key) + where TDocument : class + { + var document = await database.GetAsync(key).ConfigureAwait(false); + return document + ?? throw new KeyNotFoundException( + $"CultMesh document '{key.Value}' was not found as {typeof(TDocument).FullName}."); + } } } diff --git a/src/GameCult.Mesh/CultMeshPrimitives.cs b/src/GameCult.Mesh/CultMeshPrimitives.cs index 49906d1c..70c451ea 100644 --- a/src/GameCult.Mesh/CultMeshPrimitives.cs +++ b/src/GameCult.Mesh/CultMeshPrimitives.cs @@ -897,6 +897,9 @@ namespace GameCult.Mesh /// Gets typed state sources this document handle depends on, when known. IReadOnlyList Sources { get; } + /// Gets whether this handle can replace the underlying document value. + bool CanReplace { get; } + /// Creates a same-schema alias presentation for another CLR document type. CultMeshDocumentHandle AsSchemaAlias() where TAlias : class; } @@ -911,11 +914,15 @@ namespace GameCult.Mesh CultDocumentRegistry.Shared.GetRequired(); private readonly CultMeshBoundLiveFeed _feed; + private readonly Func? _replace; /// Creates a document handle from a Verse-bound live feed. - public CultMeshDocumentHandle(CultMeshBoundLiveFeed feed) + public CultMeshDocumentHandle( + CultMeshBoundLiveFeed feed, + Func? replace = null) { _feed = feed ?? throw new ArgumentNullException(nameof(feed)); + _replace = replace; } /// Gets the semantic document id. @@ -945,6 +952,9 @@ namespace GameCult.Mesh /// Gets the underlying live feed used by this document handle. public CultMeshLiveFeed Feed => _feed.Feed; + /// Gets whether this handle can replace the underlying document value. + public bool CanReplace => _replace != null; + /// Reads one coherent document snapshot. public Task LatestAsync() { @@ -964,6 +974,18 @@ namespace GameCult.Mesh return Watch().Subscribe(onNext); } + /// Replaces the underlying document when this handle is backed by mutable state. + public Task ReplaceAsync(TDocument value) + { + if (value == null) throw new ArgumentNullException(nameof(value)); + if (_replace == null) + { + throw new NotSupportedException($"Document handle '{DocumentId}' is read-only."); + } + + return _replace(value); + } + /// Creates a same-schema alias presentation for another CLR document type. public CultMeshDocumentHandle AsSchemaAlias() where TAlias : class { @@ -979,22 +1001,33 @@ namespace GameCult.Mesh var aliasFeed = new CultMeshLiveFeed( DocumentId, - async (parameters, context) => ConvertDocument( + async (parameters, context) => ConvertDocument( await Feed.SnapshotAsync(parameters, context).ConfigureAwait(false)), (parameters, context) => Feed .Watch(parameters, context) - .Select(ConvertDocument), + .Select(ConvertDocument), Sources, RouteHint); - return new CultMeshDocumentHandle(aliasFeed.Bind(Context)); + Func? replace = _replace == null + ? null + : value => _replace(ConvertDocument(value)); + + return new CultMeshDocumentHandle(aliasFeed.Bind(Context), replace); } - private static TAlias ConvertDocument(TDocument document) where TAlias : class + private static TTarget ConvertDocument(TSource document) + where TSource : class + where TTarget : class { if (document == null) throw new ArgumentNullException(nameof(document)); - var payload = CultDocumentMessagePackSerialization.SerializeUntyped(document, typeof(TDocument)); - return (TAlias)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(TAlias), payload); + if (document is TTarget alreadyTyped) + { + return alreadyTyped; + } + + var payload = CultDocumentMessagePackSerialization.SerializeUntyped(document, typeof(TSource)); + return (TTarget)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(TTarget), payload); } } diff --git a/src/GameCult.Mesh/docs/public-api.md b/src/GameCult.Mesh/docs/public-api.md index 30044d6e..507b82d7 100644 --- a/src/GameCult.Mesh/docs/public-api.md +++ b/src/GameCult.Mesh/docs/public-api.md @@ -162,11 +162,14 @@ portable machinery that makes it feel native. `CultMeshVerse.BindLiveFeed(...)`. - `CultMeshDocumentHandle` is the typed reactive document edge for CultCache/CultNet state. It exposes document metadata, one coherent - `LatestAsync()` read, and a `Watch()` stream without forcing callers through - transport or projection layers. Same-schema CLR aliases can be requested with - `AsSchemaAlias()`; CultMesh verifies the shared + `LatestAsync()` read, a `Watch()` stream, and `ReplaceAsync(...)` when the + handle is backed by mutable state. Callers can bind a projected live feed, a + local `CultCache` record, a distributed `CultNetDatabase` record, or a + `CultMeshNode` record through the same surface instead of walking transport + and projection layers themselves. Same-schema CLR aliases can be requested + with `AsSchemaAlias()`; CultMesh verifies the shared `[CultDocument(schemaName, schemaVersion)]` identity and uses the shared - CultCache MessagePack codec for conversion. + CultCache MessagePack codec for read/watch/replace conversion. - `CultMeshProjectionRecipe` names a reusable projection from typed source state into derived state. It records source handles, route hints, and projection execution, and can be exposed as a typed query @@ -216,6 +219,22 @@ await movePilot.InvokeAsync(moveRequest, idempotencyKey); A single typed document can be surfaced the same way: +```csharp +var stationStock = CultMesh.Document( + node, + new CultRecordKey("station:starbridge:stock"), + verse); + +var stock = await stationStock.LatestAsync(); +using var watch = stationStock.Watch(RenderStock); + +var uiAlias = stationStock.AsSchemaAlias(); +await uiAlias.ReplaceAsync(updatedStockFromUi); +``` + +Projected or derived documents can use the same handle shape with explicit +snapshot/watch delegates: + ```csharp var cockpit = CultMesh.Document( "aetheria.ship.cockpit.current", diff --git a/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs b/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs index 7985144a..1324561c 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading.Tasks; using FluentAssertions; using GameCult.Caching; +using GameCult.Networking; using MessagePack; using NUnit.Framework; using R3; @@ -697,6 +698,92 @@ public sealed class CultMeshStreamingTests .WithMessage("*tests.mesh_other*tests.mesh_note*"); } + [Test] + public async Task DocumentHandle_ReadsWatchesAndReplacesCultCacheRecords() + { + var cache = new CultCache(); + var key = new CultRecordKey("mesh-note:cache"); + await cache.UpsertAsync(new MeshNoteDocument + { + Schema = "tests.mesh_note.v1", + Text = "cache-initial", + Revision = 1 + }, new CultRecordHandle(key)); + + var handle = CultMesh.Document( + cache, + key, + CultMesh.Verse("starbridge", "unity-pilot")); + var alias = handle.AsSchemaAlias(); + + handle.CanReplace.Should().BeTrue(); + alias.CanReplace.Should().BeTrue(); + handle.DocumentId.Should().Be(key.Value); + handle.Sources.Should().ContainSingle().Which.SchemaId.Should().Be(handle.SchemaId); + + var snapshot = await alias.LatestAsync(); + snapshot.Text.Should().Be("cache-initial"); + + MeshNoteAliasDocument observed = null!; + using var subscription = alias.Watch(value => observed = value); + await alias.ReplaceAsync(new MeshNoteAliasDocument + { + Schema = "tests.mesh_note.v1", + Text = "cache-replaced", + Revision = 2 + }); + + cache.Get(key)!.Text.Should().Be("cache-replaced"); + observed.Text.Should().Be("cache-replaced"); + observed.Revision.Should().Be(2); + } + + [Test] + public async Task DocumentHandle_ReplacesThroughCultMeshNodeDatabase() + { + using var directory = new TemporaryDirectory(); + using var node = await CultMesh.CreateNodeAsync( + Path.Combine(directory.Path, "mesh-node.cc"), + new CultMeshNodeOptions + { + DatabaseOptions = new CultNetDatabaseOptions + { + RuntimeId = "node-runtime", + Shards = new[] + { + new CultNetShardDescriptor( + "mesh", + "node-runtime", + epoch: 1, + isPrimary: true, + schemaIds: new[] { CultDocumentRegistry.Shared.GetRequired().SchemaId }) + } + }, + StartServer = false + }); + var key = new CultRecordKey("mesh-note:node"); + + var handle = CultMesh.Document( + node, + key, + CultMesh.Verse("starbridge", "unity-pilot")); + var alias = handle.AsSchemaAlias(); + + MeshNoteDocument observed = null!; + using var subscription = handle.Watch(value => observed = value); + await alias.ReplaceAsync(new MeshNoteAliasDocument + { + Schema = "tests.mesh_note.v1", + Text = "node-replaced", + Revision = 3 + }); + + var snapshot = await handle.LatestAsync(); + snapshot.Text.Should().Be("node-replaced"); + observed.Text.Should().Be("node-replaced"); + observed.Revision.Should().Be(3); + } + [Test] public void SurfaceCatalog_DescribesTypedRuntimeSurfaces() { @@ -1039,6 +1126,27 @@ public sealed class CultMeshStreamingTests return catalog; } + private sealed class TemporaryDirectory : IDisposable + { + public TemporaryDirectory() + { + Path = System.IO.Path.Combine( + System.IO.Path.GetTempPath(), + "cultmesh-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public void Dispose() + { + if (Directory.Exists(Path)) + { + Directory.Delete(Path, recursive: true); + } + } + } + [CultDocument("tests.mesh_managed_player", "tests.mesh_managed_player.v1")] private sealed class MeshManagedPlayer {