From a6172aa586b427f955720996a56917897e9c7f31 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 27 Jun 2026 17:36:35 +0100 Subject: [PATCH] Add CultMesh scoped snapshot helpers --- src/GameCult.Mesh/CultMeshSnapshots.cs | 257 ++++++++++++++++++ .../CultMeshStreamingTests.cs | 63 +++++ 2 files changed, 320 insertions(+) create mode 100644 src/GameCult.Mesh/CultMeshSnapshots.cs diff --git a/src/GameCult.Mesh/CultMeshSnapshots.cs b/src/GameCult.Mesh/CultMeshSnapshots.cs new file mode 100644 index 00000000..986b901f --- /dev/null +++ b/src/GameCult.Mesh/CultMeshSnapshots.cs @@ -0,0 +1,257 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using GameCult.Networking; + +namespace GameCult.Mesh +{ + /// + /// Options for one scoped CultNet snapshot request. + /// + public sealed class CultMeshSnapshotRequestOptions + { + /// Gets or sets schema ids to request. Empty means no schema filter. + public IReadOnlyList? SchemaIds { get; set; } + + /// Gets or sets record keys to request. Empty means no record-key filter. + public IReadOnlyList? RecordKeys { get; set; } + + /// Gets or sets the target shard id, when the endpoint is shard-aware. + public string? ShardId { get; set; } + + /// Gets or sets the target shard epoch, when the endpoint is shard-aware. + public long? ShardEpoch { get; set; } + + /// Gets or sets the response timeout. + public TimeSpan ResponseTimeout { get; set; } = TimeSpan.FromSeconds(5); + + /// Gets or sets the connection timeout. + public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(5); + + /// Gets or sets the message id prefix used for snapshot requests. + public string? MessageIdPrefix { get; set; } + + /// Gets or sets client security options for endpoint-created LiteNetLib clients. + public ClientSecurityOptions? Security { get; set; } + + /// Gets or sets a callback used to configure endpoint-created LiteNetLib clients. + public Action? ConfigureClient { get; set; } + + /// Gets or sets a custom schema client factory. + public Func? CreateClient { get; set; } + + /// Gets or sets the runtime id used by endpoint-created RUDP clients. + public string? RudpRuntimeId { get; set; } + + /// Gets or sets the connection id used by endpoint-created RUDP clients. + public uint RudpConnectionId { get; set; } = 0x43554c54; + + /// Gets or sets the connect payload used by endpoint-created RUDP clients. + public string RudpConnectPayload { get; set; } = "cultnet-schema-rudp"; + + /// Gets or sets the maximum fragment size used by endpoint-created RUDP clients. + public int RudpMaxFragmentBytes { get; set; } = 1024; + + /// Gets or sets the resend delay used by endpoint-created RUDP clients. + public long RudpResendDelayMs { get; set; } = 25; + } + + public static partial class CultMesh + { + /// + /// Fetches one scoped raw CultNet snapshot from an endpoint. + /// + public static Task FetchSnapshotAsync( + string endpoint, + CultMeshSnapshotRequestOptions? options = null) + { + if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); + var resolvedOptions = options ?? new CultMeshSnapshotRequestOptions(); + return FetchSnapshotAsync(CreateSnapshotClient(endpoint, resolvedOptions), endpoint, resolvedOptions); + } + + /// + /// Fetches one scoped raw CultNet snapshot through a caller-provided schema client factory. + /// + public static async Task FetchSnapshotAsync( + Func createClient, + string endpoint, + CultMeshSnapshotRequestOptions? options = null) + { + if (createClient == null) throw new ArgumentNullException(nameof(createClient)); + if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); + + var resolvedOptions = options ?? new CultMeshSnapshotRequestOptions(); + var messageId = CreateSnapshotMessageId(resolvedOptions); + var completion = new TaskCompletionSource( + TaskCreationOptions.RunContinuationsAsynchronously); + using var client = createClient(); + client.OnCultNet(response => + { + if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal)) + completion.TrySetResult(response); + }); + client.OnCultNet(error => + completion.TrySetException(new InvalidOperationException(error.Error))); + + var (host, port) = CultNetSchemaWriteForwarder.ParseEndpoint(endpoint); + client.Connect(host, port); + await WaitForSnapshotClientConnectionAsync(client, endpoint, resolvedOptions.ConnectTimeout) + .ConfigureAwait(false); + client.SendCultNet(new CultNetSnapshotRequestMessage + { + MessageId = messageId, + SchemaIds = CleanSnapshotFilter(resolvedOptions.SchemaIds), + RecordKeys = CleanSnapshotFilter(resolvedOptions.RecordKeys), + ShardId = string.IsNullOrWhiteSpace(resolvedOptions.ShardId) ? null : resolvedOptions.ShardId, + ShardEpoch = resolvedOptions.ShardEpoch + }); + + return await WaitForSnapshotResponseAsync( + completion.Task, + endpoint, + resolvedOptions, + messageId) + .ConfigureAwait(false); + } + + /// + /// Fetches a scoped raw CultNet snapshot and applies it into the node's cache. + /// + public static async Task> ApplySnapshotAsync( + CultMeshNode node, + string endpoint, + CultMeshSnapshotRequestOptions? options = null) + { + if (node == null) throw new ArgumentNullException(nameof(node)); + var snapshot = await FetchSnapshotAsync(endpoint, options).ConfigureAwait(false); + return await node.Database.Documents.ApplyRawSnapshotResponseAsync(node.Cache, snapshot).ConfigureAwait(false); + } + + /// + /// Fetches a scoped raw CultNet snapshot and decodes documents assignable to the requested type. + /// + public static async Task> FetchSnapshotDocumentsAsync( + string endpoint, + CultMeshSnapshotRequestOptions? options = null, + CultNetDocumentRegistry? registry = null) + where TDocument : class + { + var snapshot = await FetchSnapshotAsync(endpoint, options).ConfigureAwait(false); + return DecodeSnapshotDocuments(snapshot, registry ?? new CultNetDocumentRegistry()); + } + + private static Func CreateSnapshotClient( + string endpoint, + CultMeshSnapshotRequestOptions options) + { + if (options.CreateClient != null) + return options.CreateClient; + + return () => + { + if (Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) && + string.Equals(uri.Scheme, "rudp", StringComparison.OrdinalIgnoreCase)) + { + return CultNetSchemaClients.CreateRudp( + string.IsNullOrWhiteSpace(options.RudpRuntimeId) + ? "cultmesh-snapshot-client" + : options.RudpRuntimeId!, + options.RudpConnectionId, + options.RudpConnectPayload, + options.RudpMaxFragmentBytes, + options.RudpResendDelayMs); + } + + return CultNetSchemaClients.CreateForEndpoint(endpoint, options.Security, options.ConfigureClient); + }; + } + + private static string CreateSnapshotMessageId(CultMeshSnapshotRequestOptions options) + { + var prefix = string.IsNullOrWhiteSpace(options.MessageIdPrefix) + ? "cultmesh:snapshot" + : options.MessageIdPrefix!; + return $"{prefix}:{Guid.NewGuid():N}"; + } + + private static async Task WaitForSnapshotClientConnectionAsync( + ICultNetSchemaClient client, + string endpoint, + TimeSpan timeout) + { + var deadline = DateTimeOffset.UtcNow + timeout; + while (!client.Connected) + { + if (DateTimeOffset.UtcNow >= deadline) + throw new TimeoutException($"Timed out connecting to CultNet snapshot endpoint {endpoint}."); + + await Task.Delay(TimeSpan.FromMilliseconds(25)).ConfigureAwait(false); + } + } + + private static async Task WaitForSnapshotResponseAsync( + Task responseTask, + string endpoint, + CultMeshSnapshotRequestOptions options, + string messageId) + { + var timeoutTask = Task.Delay(options.ResponseTimeout); + var completed = await Task.WhenAny(responseTask, timeoutTask).ConfigureAwait(false); + if (completed != responseTask) + { + throw new TimeoutException( + $"Timed out waiting for CultNet snapshot response '{messageId}' from {endpoint} " + + $"for schemas [{string.Join(", ", CleanSnapshotFilter(options.SchemaIds) ?? Array.Empty())}] " + + $"and records [{string.Join(", ", CleanSnapshotFilter(options.RecordKeys) ?? Array.Empty())}]."); + } + + return await responseTask.ConfigureAwait(false); + } + + private static string[]? CleanSnapshotFilter(IReadOnlyList? values) + { + if (values is not { Count: > 0 }) + return null; + + var filtered = values + .Where(value => !string.IsNullOrWhiteSpace(value)) + .Distinct(StringComparer.Ordinal) + .ToArray(); + return filtered.Length == 0 ? null : filtered; + } + + private static IReadOnlyList DecodeSnapshotDocuments( + CultNetSnapshotResponseRawMessage snapshot, + CultNetDocumentRegistry registry) + where TDocument : class + { + if (snapshot == null) throw new ArgumentNullException(nameof(snapshot)); + if (registry == null) throw new ArgumentNullException(nameof(registry)); + + var documents = new List(snapshot.Documents.Length); + foreach (var record in snapshot.Documents) + { + if (record == null) + continue; + + var binding = registry.GetBySchemaId(record.SchemaId); + if (binding == null || !typeof(TDocument).IsAssignableFrom(binding.DocumentType)) + continue; + + if (!string.Equals(record.PayloadEncoding, "messagepack", StringComparison.Ordinal)) + { + throw new InvalidOperationException( + $"CultNet raw document payloadEncoding must be \"messagepack\", not \"{record.PayloadEncoding}\"."); + } + + documents.Add((TDocument)binding.PayloadDeserializer(record.Payload)); + } + + return documents; + } + } +} diff --git a/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs b/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs index ae862f9f..c1a9240d 100644 --- a/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs +++ b/tests/GameCult.Mesh.Tests/CultMeshStreamingTests.cs @@ -1037,6 +1037,69 @@ public sealed class CultMeshStreamingTests (await aliasSchemaHandle.LatestAsync()).Text.Should().Be("record-key-fallback"); } + [Test] + public async Task SnapshotHelpers_FetchApplyAndDecodeScopedSnapshots() + { + var sourceCache = new CultCache(); + var targetCache = new CultCache(); + var registry = new CultNetDocumentRegistry(CultDocumentRegistry.Shared); + registry.Register(CultNetDocumentBinding.ForDocument(sourceCache.Registry)); + var key = new CultRecordKey("mesh-note:snapshot-helper"); + await sourceCache.UpsertAsync(new MeshPublicationNoteDocument + { + Schema = "tests.mesh_publication_note.v1", + Text = "snapshot-helper", + Revision = 11 + }, new CultRecordHandle(key)); + var requests = new List(); + var endpoint = "cultnet://snapshot-helper.test:3075"; + var options = new CultMeshSnapshotRequestOptions + { + RecordKeys = new[] { key.Value }, + ShardId = "primary", + ShardEpoch = 7, + MessageIdPrefix = "mesh-test-scoped-snapshot", + CreateClient = () => new MeshSnapshotSchemaClient(request => + { + requests.Add(request); + return registry.CreateRawSnapshotResponse(sourceCache, request.MessageId, request); + }) + }; + + var snapshot = await CultMesh.FetchSnapshotAsync(endpoint, options); + var decoded = await CultMesh.FetchSnapshotDocumentsAsync( + endpoint, + options, + registry); + using var node = await CultMesh.CreateNodeAsync( + Path.Combine(Path.GetTempPath(), $"cultmesh-snapshot-helper-{Guid.NewGuid():N}.ccmp"), + new CultMeshNodeOptions + { + StartServer = false, + CacheOptions = new CultCacheOpenOptions + { + Registry = targetCache.Registry, + PullOnOpen = false + }, + DatabaseOptions = new CultNetDatabaseOptions + { + DocumentRegistry = registry + } + }); + var applied = await CultMesh.ApplySnapshotAsync(node, endpoint, options); + + snapshot.Documents.Should().ContainSingle().Which.RecordKey.Should().Be(key.Value); + decoded.Should().ContainSingle().Which.Text.Should().Be("snapshot-helper"); + applied.Should().ContainSingle(); + node.Cache.Get(key)!.Revision.Should().Be(11); + requests.Should().HaveCount(3); + requests.Should().OnlyContain(request => + request.RecordKeys!.SequenceEqual(new[] { key.Value }) && + request.ShardId == "primary" && + request.ShardEpoch == 7 && + request.MessageId.StartsWith("mesh-test-scoped-snapshot:", StringComparison.Ordinal)); + } + [Test] public async Task CollectionHandle_ReadsAndWatchesDatabaseCollectionsByIndex() {