using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using GameCult.Caching; using GameCult.Caching.MessagePack; using GameCult.Networking; using MessagePack; namespace GameCult.Mesh { /// /// Options for one scoped CultNet snapshot request. /// public sealed record CultMeshSnapshotRequestOptions { /// Gets or sets the selection to request. Absent selects every schema and key. public CultNetSelection? Selection { 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; } /// /// Reuses one connected CultNet schema client for an ordered sequence of snapshot requests. /// public sealed class CultMeshSnapshotSession : IDisposable { private readonly string _endpoint; private readonly CultMeshSnapshotRequestOptions _defaults; private readonly ICultNetSchemaClient _client; private readonly CultMeshSession? _sharedSession; private readonly IDisposable? _responseSubscription; private readonly IDisposable? _errorSubscription; private readonly CultNetDocumentRegistry _registry; private readonly SemaphoreSlim _requests = new(1, 1); private readonly object _completionLock = new(); private TaskCompletionSource? _completion; private string? _messageId; private bool _disposed; internal CultMeshSnapshotSession( string endpoint, CultMeshSnapshotRequestOptions options, CultNetDocumentRegistry? registry) { _endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Value must be non-empty.", nameof(endpoint)) : endpoint; _defaults = options with { }; _registry = registry ?? new CultNetDocumentRegistry(); _client = CultMesh.CreateSnapshotClient(endpoint, _defaults)(); _client.OnCultNet(OnResponse); _client.OnCultNet(OnError); var (host, port) = CultNetSchemaWriteForwarder.ParseEndpoint(endpoint); _client.Connect(host, port); } private CultMeshSnapshotSession( CultMeshSession session, CultMeshSnapshotRequestOptions options, CultNetDocumentRegistry? registry) { _sharedSession = session ?? throw new ArgumentNullException(nameof(session)); _endpoint = session.State.Path?.Endpoint ?? session.Target.AuthorityRuntimeId; _defaults = options with { }; _registry = registry ?? new CultNetDocumentRegistry(); _client = session.Channel; _responseSubscription = session.OnCultNet(OnResponse); _errorSubscription = session.OnCultNet(OnError); } public static async Task ConnectAsync( CultMeshSessionManager sessions, CultMeshSessionTarget target, CultMeshSnapshotRequestOptions options, CultNetDocumentRegistry? registry = null, CancellationToken cancellationToken = default) { if (sessions == null) throw new ArgumentNullException(nameof(sessions)); var session = await sessions.ConnectAsync(target, CultMeshProtocols.Documents, cancellationToken).ConfigureAwait(false); return new CultMeshSnapshotSession(session, options ?? new CultMeshSnapshotRequestOptions(), registry); } public static async Task ConnectAsync( CultMeshSessionManager sessions, CultMeshSessionTarget target, CultMeshProtocolId protocol, CultMeshSnapshotRequestOptions options, CultNetDocumentRegistry? registry = null, CancellationToken cancellationToken = default) { if (sessions == null) throw new ArgumentNullException(nameof(sessions)); var session = await sessions.ConnectAsync(target, protocol, cancellationToken).ConfigureAwait(false); return new CultMeshSnapshotSession(session, options ?? new CultMeshSnapshotRequestOptions(), registry); } /// Fetches one raw snapshot while retaining the underlying endpoint connection. public async Task FetchSnapshotAsync( IReadOnlyList? schemaIds = null, IReadOnlyList? recordKeys = null) { ThrowIfDisposed(); await _requests.WaitAsync().ConfigureAwait(false); try { await CultMesh.WaitForSnapshotClientConnectionAsync( _client, _endpoint, _defaults.ConnectTimeout, (_client as ICultNetSchemaClientHealth)?.BackgroundFailure) .ConfigureAwait(false); var selection = CultMesh.OverlaySelection(_defaults.Selection, schemaIds, recordKeys); CultMesh.EnsureV0Compatible(selection); var options = _defaults with { Selection = selection }; var messageId = CultMesh.CreateSnapshotMessageId(options); var completion = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously); lock (_completionLock) { _messageId = messageId; _completion = completion; } _client.SendCultNet(new CultNetSnapshotRequestMessage { MessageId = messageId, SchemaIds = selection.Schemas, RecordKeys = selection.Keys, ShardId = string.IsNullOrWhiteSpace(options.ShardId) ? null : options.ShardId, ShardEpoch = options.ShardEpoch }); return await CultMesh.WaitForSnapshotResponseAsync( completion.Task, _endpoint, options, messageId, (_client as ICultNetSchemaClientHealth)?.BackgroundFailure) .ConfigureAwait(false); } finally { lock (_completionLock) { _messageId = null; _completion = null; } _requests.Release(); } } /// Fetches and decodes typed documents over the retained endpoint connection. public async Task> FetchDocumentsAsync( IReadOnlyList? recordKeys = null, IReadOnlyList? schemaIds = null) where TDocument : class { var descriptor = CultDocumentRegistry.Shared.GetRequired(); var selection = CultMesh.ResolveDefaultSelection(schemaIds, recordKeys, descriptor); var snapshot = await FetchSnapshotAsync(selection.Schemas, selection.Keys).ConfigureAwait(false); return CultMesh.DecodeSnapshotDocuments(snapshot, _registry); } /// Closes the retained endpoint connection and rejects any active request. public void Dispose() { if (_disposed) return; _disposed = true; lock (_completionLock) _completion?.TrySetException(new ObjectDisposedException(nameof(CultMeshSnapshotSession))); _responseSubscription?.Dispose(); _errorSubscription?.Dispose(); if (_sharedSession == null) _client.Dispose(); _requests.Dispose(); } private void OnResponse(CultNetSnapshotResponseRawMessage response) { lock (_completionLock) { if (string.Equals(response.MessageId, _messageId, StringComparison.Ordinal)) _completion?.TrySetResult(response); } } private void OnError(CultNetErrorMessage error) { lock (_completionLock) _completion?.TrySetException(new InvalidOperationException(error.Error)); } private void ThrowIfDisposed() { if (_disposed) throw new ObjectDisposedException(nameof(CultMeshSnapshotSession)); } } /// /// Options for a typed remote snapshot surface bound to one CultNet endpoint. /// public sealed class CultMeshSnapshotEndpointOptions { /// Gets or sets the Verse context used by handles from this endpoint. public CultMeshVerseContext? Context { get; set; } /// Gets or sets the document registry used for raw snapshot payload decoding. public CultNetDocumentRegistry? DocumentRegistry { get; set; } /// Gets or sets request options applied to each snapshot fetch. public CultMeshSnapshotRequestOptions? Request { get; set; } /// Gets or sets the source id advertised by diagnostics. Defaults to the endpoint. public string? SourceId { get; set; } /// Gets or sets the route hint for resulting handles. public CultMeshRouteHint? RouteHint { get; set; } /// Gets or sets the polling interval for watch fallback. public TimeSpan PollInterval { get; set; } = TimeSpan.FromMilliseconds(250); } /// /// Describes one typed document handle to bind from a snapshot endpoint. /// public interface ICultMeshSnapshotDocumentBinding { /// Gets the CLR document type requested by this binding. Type DocumentType { get; } /// Gets the remote record key to read. string RecordKey { get; } /// Gets the optional semantic document id for the resulting handle. string? DocumentId { get; } /// Binds this document request to an endpoint-backed handle. ICultMeshDocumentHandle Bind(CultMeshSnapshotEndpoint endpoint); /// Binds this document request to an endpoint-backed handle that syncs into a local node before returning values. ICultMeshDocumentHandle BindSynced(CultMeshSnapshotEndpoint endpoint, CultMeshNode node, bool flush); } /// /// Describes one typed document handle to bind from a snapshot endpoint. /// public sealed class CultMeshSnapshotDocumentBinding : ICultMeshSnapshotDocumentBinding where TDocument : class { internal CultMeshSnapshotDocumentBinding(string recordKey, string? documentId) { RecordKey = string.IsNullOrWhiteSpace(recordKey) ? throw new ArgumentException("Value must be non-empty.", nameof(recordKey)) : recordKey; DocumentId = documentId; } /// public Type DocumentType => typeof(TDocument); /// public string RecordKey { get; } /// public string? DocumentId { get; } /// public ICultMeshDocumentHandle Bind(CultMeshSnapshotEndpoint endpoint) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); return endpoint.Document(RecordKey, DocumentId); } /// public ICultMeshDocumentHandle BindSynced(CultMeshSnapshotEndpoint endpoint, CultMeshNode node, bool flush) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); return endpoint.SyncedDocument(node, RecordKey, DocumentId, flush); } } /// /// Result from syncing a remote snapshot into a local CultMesh node. /// public sealed class CultMeshSnapshotSyncResult { internal CultMeshSnapshotSyncResult( CultNetSnapshotResponseRawMessage snapshot, IReadOnlyList appliedDocuments) { Snapshot = snapshot ?? throw new ArgumentNullException(nameof(snapshot)); AppliedDocuments = appliedDocuments ?? throw new ArgumentNullException(nameof(appliedDocuments)); } /// Gets the raw snapshot that was fetched from the endpoint. public CultNetSnapshotResponseRawMessage Snapshot { get; } /// Gets the documents applied into the local node cache. public IReadOnlyList AppliedDocuments { get; } /// Gets the number of documents applied into the local node cache. public int AppliedCount => AppliedDocuments.Count; /// Gets the source shard log sequence reported by the snapshot, when present. public long ShardLogSequence => Snapshot.ShardLogSequence ?? 0L; } /// /// Snapshot endpoint view with a local node sync policy already bound. /// public sealed class CultMeshSyncedSnapshotEndpoint { internal CultMeshSyncedSnapshotEndpoint( CultMeshSnapshotEndpoint endpoint, CultMeshNode node, bool flush) { Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); Node = node ?? throw new ArgumentNullException(nameof(node)); Flush = flush; } /// Gets the remote endpoint that provides snapshots. public CultMeshSnapshotEndpoint Endpoint { get; } /// Gets the local node snapshots are synced into. public CultMeshNode Node { get; } /// Gets whether each sync should flush the local node afterward. public bool Flush { get; } /// Creates a typed document handle that syncs into the local node before returning values. public CultMeshDocumentHandle Document( string recordKey, string? documentId = null) where TDocument : class { return Endpoint.SyncedDocument(Node, recordKey, documentId, Flush); } /// Creates a schema-aware catalog from typed endpoint bindings that sync into the local node before returning values. public CultMeshDocumentCatalog Documents(params ICultMeshSnapshotDocumentBinding[] documents) { return Endpoint.SyncedDocuments(Node, Flush, documents); } } /// /// Typed snapshot surface for one remote CultNet endpoint. /// public sealed class CultMeshSnapshotEndpoint { internal CultMeshSnapshotEndpoint(string endpoint, CultMeshSnapshotEndpointOptions? options) { Endpoint = string.IsNullOrWhiteSpace(endpoint) ? throw new ArgumentException("Value must be non-empty.", nameof(endpoint)) : endpoint; var resolvedOptions = options ?? new CultMeshSnapshotEndpointOptions(); Context = resolvedOptions.Context ?? CultMesh.Verse("remote", "cultmesh-snapshot-client").Context; DocumentRegistry = resolvedOptions.DocumentRegistry ?? new CultNetDocumentRegistry(); Request = resolvedOptions.Request is null ? new CultMeshSnapshotRequestOptions() : resolvedOptions.Request with { }; RouteHint = resolvedOptions.RouteHint ?? new CultMeshRouteHint(CultMeshLocalityKind.Network, Endpoint); SourceId = string.IsNullOrWhiteSpace(resolvedOptions.SourceId) ? Endpoint : resolvedOptions.SourceId!; PollInterval = resolvedOptions.PollInterval; } /// Gets the endpoint this typed surface reads from. public string Endpoint { get; } /// Gets the Verse context used by document handles from this endpoint. public CultMeshVerseContext Context { get; } /// Gets the document registry used for raw snapshot payload decoding. public CultNetDocumentRegistry DocumentRegistry { get; } /// Gets request options applied to each snapshot fetch. public CultMeshSnapshotRequestOptions Request { get; } /// Gets the source id advertised by diagnostics. public string SourceId { get; } /// Gets the route hint for resulting handles. public CultMeshRouteHint RouteHint { get; } /// Gets the polling interval for watch fallback. public TimeSpan PollInterval { get; } /// Returns a view of this endpoint whose typed document handles sync into the supplied local node. public CultMeshSyncedSnapshotEndpoint SyncTo(CultMeshNode node, bool flush = false) { return new CultMeshSyncedSnapshotEndpoint(this, node, flush); } /// Fetches one raw snapshot with this endpoint's configured request policy. public Task FetchSnapshotAsync( IReadOnlyList? schemaIds = null, IReadOnlyList? recordKeys = null) { return CultMesh.FetchSnapshotAsync(Endpoint, CreateRequest(schemaIds, recordKeys)); } /// Fetches one snapshot and applies it into the node's cache. public async Task SyncSnapshotAsync( CultMeshNode node, IReadOnlyList? schemaIds = null, IReadOnlyList? recordKeys = null, bool flush = false) { if (node == null) throw new ArgumentNullException(nameof(node)); var snapshot = await FetchSnapshotAsync(schemaIds, recordKeys).ConfigureAwait(false); var applied = await node.Database.Documents.ApplyRawSnapshotResponseAsync(node.Cache, snapshot) .ConfigureAwait(false); if (flush) await node.FlushAsync().ConfigureAwait(false); return new CultMeshSnapshotSyncResult(snapshot, applied); } /// Fetches and decodes documents assignable to the requested type or matching its schema. public Task> FetchDocumentsAsync( IReadOnlyList? recordKeys = null, IReadOnlyList? schemaIds = null) where TDocument : class { var descriptor = CultDocumentRegistry.Shared.GetRequired(); var selection = CultMesh.ResolveDefaultSelection(schemaIds, recordKeys, descriptor); return CultMesh.FetchSnapshotDocumentsAsync( Endpoint, CreateRequest(selection.Schemas, selection.Keys), DocumentRegistry); } /// Fetches typed documents and syncs their raw snapshot into the node's cache. public async Task> SyncDocumentsAsync( CultMeshNode node, IReadOnlyList? recordKeys = null, IReadOnlyList? schemaIds = null, bool flush = false) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var selection = CultMesh.ResolveDefaultSelection(schemaIds, recordKeys, descriptor); var result = await SyncSnapshotAsync( node, selection.Schemas, selection.Keys, flush) .ConfigureAwait(false); return CultMesh.DecodeSnapshotDocuments(result.Snapshot, DocumentRegistry); } /// Fetches one typed document by record key. public async Task FetchDocumentAsync(string recordKey) where TDocument : class { if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Value must be non-empty.", nameof(recordKey)); var documents = await FetchDocumentsAsync(new[] { recordKey }).ConfigureAwait(false); return documents.FirstOrDefault() ?? throw new InvalidOperationException( $"CultNet snapshot endpoint '{Endpoint}' did not return {typeof(TDocument).FullName} record '{recordKey}'."); } /// Fetches one typed document by record key and syncs it into the node's cache. public async Task SyncDocumentAsync( CultMeshNode node, string recordKey, bool flush = false) where TDocument : class { if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Value must be non-empty.", nameof(recordKey)); var documents = await SyncDocumentsAsync(node, new[] { recordKey }, flush: flush) .ConfigureAwait(false); return documents.FirstOrDefault() ?? throw new InvalidOperationException( $"CultNet snapshot endpoint '{Endpoint}' did not return {typeof(TDocument).FullName} record '{recordKey}'."); } /// Creates a typed document handle that fetches one endpoint record and syncs it into a local node before returning values. public CultMeshDocumentHandle SyncedDocument( CultMeshNode node, string recordKey, string? documentId = null, bool flush = false) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Value must be non-empty.", nameof(recordKey)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var sources = new[] { CultMesh.ProjectionSource($"{SourceId}:{recordKey}", descriptor.SchemaId, "synced CultNet snapshot endpoint") }; var watch = CultMesh.PollingQueryWatcher( async (_parameters, _context) => await SyncDocumentAsync(node, recordKey, flush).ConfigureAwait(false), new CultMeshPollingWatchOptions(PollInterval)); return CultMesh.Document( string.IsNullOrWhiteSpace(documentId) ? recordKey : documentId!, Context, _ => SyncDocumentAsync(node, recordKey, flush), queryContext => watch(CultMeshDocumentQueryParameters.Empty, queryContext), sources, RouteHint); } /// Creates a typed document handle over one remote endpoint record. public CultMeshDocumentHandle Document( string recordKey, string? documentId = null) where TDocument : class { if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Value must be non-empty.", nameof(recordKey)); var descriptor = CultDocumentRegistry.Shared.GetRequired(); var sources = new[] { CultMesh.ProjectionSource($"{SourceId}:{recordKey}", descriptor.SchemaId, "CultNet snapshot endpoint") }; var watch = CultMesh.PollingQueryWatcher( async (_parameters, _context) => await FetchDocumentAsync(recordKey).ConfigureAwait(false), new CultMeshPollingWatchOptions(PollInterval)); return CultMesh.Document( string.IsNullOrWhiteSpace(documentId) ? recordKey : documentId!, Context, _ => FetchDocumentAsync(recordKey), queryContext => watch(CultMeshDocumentQueryParameters.Empty, queryContext), sources, RouteHint); } /// Creates a schema-aware catalog over endpoint-backed document handles. public CultMeshDocumentCatalog Documents(params ICultMeshDocumentHandle[] documents) { return CultMesh.Documents(documents); } /// Creates a schema-aware catalog from endpoint-backed typed document bindings. public CultMeshDocumentCatalog Documents(params ICultMeshSnapshotDocumentBinding[] documents) { if (documents == null) throw new ArgumentNullException(nameof(documents)); return CultMesh.Documents(documents.Select(document => { if (document == null) throw new ArgumentNullException(nameof(documents)); return document.Bind(this); })); } /// Creates a schema-aware catalog from typed endpoint bindings that sync into a local node before returning values. public CultMeshDocumentCatalog SyncedDocuments( CultMeshNode node, params ICultMeshSnapshotDocumentBinding[] documents) { return SyncedDocuments(node, flush: false, documents); } /// Creates a schema-aware catalog from typed endpoint bindings that sync into a local node before returning values. public CultMeshDocumentCatalog SyncedDocuments( CultMeshNode node, bool flush = false, params ICultMeshSnapshotDocumentBinding[] documents) { if (node == null) throw new ArgumentNullException(nameof(node)); if (documents == null) throw new ArgumentNullException(nameof(documents)); return CultMesh.Documents(documents.Select(document => { if (document == null) throw new ArgumentNullException(nameof(documents)); return document.BindSynced(this, node, flush); })); } private CultMeshSnapshotRequestOptions CreateRequest( IReadOnlyList? schemaIds, IReadOnlyList? recordKeys) { var request = Request with { Selection = CultMesh.OverlaySelection(Request.Selection, schemaIds, recordKeys) }; if (string.IsNullOrWhiteSpace(request.RudpRuntimeId)) request.RudpRuntimeId = Context.RuntimeId; if (string.IsNullOrWhiteSpace(request.MessageIdPrefix)) request.MessageIdPrefix = $"cultmesh:{Context.RuntimeId}:snapshot"; return request; } } public static partial class CultMesh { /// /// Binds one CultNet endpoint as a typed snapshot surface. /// public static CultMeshSnapshotEndpoint SnapshotEndpoint( string endpoint, CultMeshSnapshotEndpointOptions? options = null) { return new CultMeshSnapshotEndpoint(endpoint, options); } /// /// Opens one reusable CultNet snapshot connection for ordered bulk document transfer. /// public static CultMeshSnapshotSession SnapshotSession( string endpoint, CultMeshSnapshotRequestOptions? options = null, CultNetDocumentRegistry? registry = null) { return new CultMeshSnapshotSession( endpoint, options ?? new CultMeshSnapshotRequestOptions(), registry); } /// /// Describes one typed document to bind from a CultMesh snapshot endpoint. /// public static CultMeshSnapshotDocumentBinding SnapshotDocument( string recordKey, string? documentId = null) where TDocument : class { return new CultMeshSnapshotDocumentBinding(recordKey, documentId); } /// /// Fetches one typed snapshot document and syncs it into a local node in one call. /// public static Task SyncDocumentFromPeerSnapshotAsync( CultMeshNode node, string endpoint, string recordKey, CultMeshSnapshotEndpointOptions? options = null, bool flush = false) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Value must be non-empty.", nameof(recordKey)); return SnapshotEndpoint(endpoint, options).SyncDocumentAsync(node, recordKey, flush); } /// /// Fetches one typed snapshot document through a caller-provided schema client and syncs it into a local node in one call. /// public static Task SyncDocumentFromPeerSnapshotAsync( CultMeshNode node, Func createClient, string endpoint, string recordKey, CultMeshSnapshotEndpointOptions? options = null, bool flush = false) where TDocument : class { if (node == null) throw new ArgumentNullException(nameof(node)); if (createClient == null) throw new ArgumentNullException(nameof(createClient)); if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Value must be non-empty.", nameof(recordKey)); var request = options?.Request is null ? new CultMeshSnapshotRequestOptions() : options.Request with { }; request.CreateClient = createClient; var resolvedOptions = new CultMeshSnapshotEndpointOptions { Context = options?.Context, DocumentRegistry = options?.DocumentRegistry, Request = request, SourceId = options?.SourceId, RouteHint = options?.RouteHint, PollInterval = options?.PollInterval ?? TimeSpan.FromMilliseconds(250) }; return SnapshotEndpoint(endpoint, resolvedOptions).SyncDocumentAsync(node, recordKey, flush); } /// /// 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(); EnsureV0Compatible(resolvedOptions.Selection); 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, (client as ICultNetSchemaClientHealth)?.BackgroundFailure) .ConfigureAwait(false); client.SendCultNet(new CultNetSnapshotRequestMessage { MessageId = messageId, SchemaIds = resolvedOptions.Selection?.Schemas, RecordKeys = resolvedOptions.Selection?.Keys, ShardId = string.IsNullOrWhiteSpace(resolvedOptions.ShardId) ? null : resolvedOptions.ShardId, ShardEpoch = resolvedOptions.ShardEpoch }); return await WaitForSnapshotResponseAsync( completion.Task, endpoint, resolvedOptions, messageId, (client as ICultNetSchemaClientHealth)?.BackgroundFailure) .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()); } internal 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); }; } /// /// Refuses, loudly and typed, any selection term the v0 CultNet wire cannot carry. Mesh keeps /// sending v0 in this cut (docs/cultnet-selection-cut.md, Self's rulings 2026-09-22): only /// schemas and keys reach the wire message, so fields, cites, /// cited, limit, cursor, descending, and any non-default /// projection are refused here instead of being silently dropped. A v1-carrying Mesh /// transport is FU-Mesh-v1, not this cut. /// internal static void EnsureV0Compatible(CultNetSelection? selection) { if (selection == null) return; // The door runs first (docs/cultnet-selection-cut.md, R-F): Mesh has no descriptor list to // check field/role reachability against, but the declaration-independent half of the door - // an empty or blank-only schemas/keys list, an unrecognised projection - applies here just // as it does inside CultNetSelectionEvaluator.Select, so Keys=[]/[""] is refused rather than // silently lowered to "every key". CultNetSelectionValidation.ValidateShape(selection); if (selection.Fields != null) throw new CultNetSelectionInvalidException("fields", null, "CultMesh sends cultnet.snapshot_request.v0 in this cut; selection.fields cannot reach the wire (FU-Mesh-v1)."); if (selection.Cites != null) throw new CultNetSelectionInvalidException("cites", null, "CultMesh sends cultnet.snapshot_request.v0 in this cut; selection.cites cannot reach the wire (FU-Mesh-v1)."); if (selection.Cited != null) throw new CultNetSelectionInvalidException("cited", null, "CultMesh sends cultnet.snapshot_request.v0 in this cut; selection.cited cannot reach the wire (FU-Mesh-v1)."); if (selection.Limit != null) throw new CultNetSelectionInvalidException("limit", null, "CultMesh sends cultnet.snapshot_request.v0 in this cut; selection.limit cannot reach the wire (FU-Mesh-v1)."); if (selection.Cursor != null) throw new CultNetSelectionInvalidException("cursor", null, "CultMesh sends cultnet.snapshot_request.v0 in this cut; selection.cursor cannot reach the wire (FU-Mesh-v1)."); if (selection.Descending) throw new CultNetSelectionInvalidException("descending", null, "CultMesh sends cultnet.snapshot_request.v0 in this cut; selection.descending cannot reach the wire (FU-Mesh-v1)."); if (selection.Projection != CultNetSelectionProjections.Header) throw new CultNetSelectionInvalidException("projection", selection.Projection, "CultMesh sends cultnet.snapshot_request.v0 in this cut; selection.projection cannot reach the wire (FU-Mesh-v1)."); } /// /// Resolves one selection for a typed convenience call: explicit /// win; otherwise an explicit - including one that lowers to an /// empty array - means no schema filter; otherwise the selection defaults to the document /// type's own schema. R-R (2026-09-22): an empty is a real filter /// (answers nothing), not "no filter", so it must not fall through to the schema default /// either. The one owner of that rule (docs/cultnet-selection-cut.md, section 4). /// internal static CultNetSelection ResolveDefaultSelection( IReadOnlyList? schemaIds, IReadOnlyList? recordKeys, CultDocumentDescriptor descriptor) { var cleanedKeys = Clean(recordKeys); var schemas = schemaIds != null ? Clean(schemaIds) : (cleanedKeys != null ? null : new[] { descriptor.SchemaId }); return new CultNetSelection { Schemas = schemas, Keys = cleanedKeys }; } /// /// Overlays explicit schema/record-key overrides onto a default selection: the caller's /// selection replaces the default wholesale rather than merging field by field, so neither /// side decides what a missing override means (docs/cultnet-selection-cut.md, Self's rulings /// 2026-09-22, S2-7). No override at all keeps the default selection untouched. /// internal static CultNetSelection OverlaySelection( CultNetSelection? defaults, IReadOnlyList? schemaIds, IReadOnlyList? recordKeys) { if (schemaIds == null && recordKeys == null) return defaults ?? new CultNetSelection(); return new CultNetSelection { Schemas = Clean(schemaIds), Keys = Clean(recordKeys) }; } // The v0-compatibility list cleaning is CultNetV0SelectionLowering's, not a second copy here // (docs/cultnet-selection-cut.md, Self's rulings 2026-09-22). private static string[]? Clean(IReadOnlyList? values) => CultNetV0SelectionLowering.Lower(values); internal static string CreateSnapshotMessageId(CultMeshSnapshotRequestOptions options) { var prefix = string.IsNullOrWhiteSpace(options.MessageIdPrefix) ? "cultmesh:snapshot" : options.MessageIdPrefix!; return $"{prefix}:{Guid.NewGuid():N}"; } internal static async Task WaitForSnapshotClientConnectionAsync( ICultNetSchemaClient client, string endpoint, TimeSpan timeout, Task? backgroundFailure = null) { var deadline = DateTimeOffset.UtcNow + timeout; while (!client.Connected) { if (backgroundFailure?.IsCompleted == true) { var error = await backgroundFailure.ConfigureAwait(false); throw new InvalidOperationException( $"CultNet snapshot client failed while connecting to {endpoint}.", error); } if (DateTimeOffset.UtcNow >= deadline) throw new TimeoutException($"Timed out connecting to CultNet snapshot endpoint {endpoint}."); await Task.Delay(TimeSpan.FromMilliseconds(25)).ConfigureAwait(false); } } internal static async Task WaitForSnapshotResponseAsync( Task responseTask, string endpoint, CultMeshSnapshotRequestOptions options, string messageId, Task? backgroundFailure = null) { var timeoutTask = Task.Delay(options.ResponseTimeout); var completed = backgroundFailure == null ? await Task.WhenAny(responseTask, timeoutTask).ConfigureAwait(false) : await Task.WhenAny(responseTask, timeoutTask, backgroundFailure).ConfigureAwait(false); if (completed == backgroundFailure) { var error = await backgroundFailure.ConfigureAwait(false); throw new InvalidOperationException( $"CultNet snapshot client failed while waiting for response '{messageId}' from {endpoint}.", error); } if (completed != responseTask) { throw new TimeoutException( $"Timed out waiting for CultNet snapshot response '{messageId}' from {endpoint} " + $"for schemas [{string.Join(", ", options.Selection?.Schemas ?? Array.Empty())}] " + $"and records [{string.Join(", ", options.Selection?.Keys ?? Array.Empty())}]."); } return await responseTask.ConfigureAwait(false); } internal 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 descriptor = CultDocumentRegistry.Shared.GetRequired(); var documents = new List(snapshot.Documents.Length); foreach (var record in snapshot.Documents) { if (record == null) continue; var binding = registry.GetBySchemaId(record.SchemaId); var canDeserializeWithBinding = binding != null && typeof(TDocument).IsAssignableFrom(binding.DocumentType); var canDeserializeAsSchemaAlias = CultNetSchemaAliasMatching.Matches(record.SchemaId, descriptor) || (binding != null && CultNetSchemaAliasMatching.Matches(binding.SchemaId, descriptor)) || CultNetDocumentRegistry.PayloadMatchesSchema(record.Payload, descriptor); if (!canDeserializeWithBinding && !canDeserializeAsSchemaAlias) continue; if (!string.Equals(record.PayloadEncoding, "messagepack", StringComparison.Ordinal)) { throw new InvalidOperationException( $"CultNet raw document payloadEncoding must be \"messagepack\", not \"{record.PayloadEncoding}\"."); } if (binding != null) { var decoded = binding.PayloadDeserializer(record.Payload); documents.Add(decoded is TDocument typed ? typed : ConvertUntypedDocument(decoded)); } else { documents.Add((TDocument)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(TDocument), record.Payload)); } } return documents; } } }