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 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;
}
///
/// 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 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 = CultMesh.CloneSnapshotRequestOptions(options);
_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);
}
/// 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 options = CultMesh.CloneSnapshotRequestOptions(_defaults);
options.SchemaIds = schemaIds ?? options.SchemaIds;
options.RecordKeys = recordKeys ?? options.RecordKeys;
var messageId = CultMesh.CreateSnapshotMessageId(options);
var completion = new TaskCompletionSource(
TaskCreationOptions.RunContinuationsAsynchronously);
lock (_completionLock)
{
_messageId = messageId;
_completion = completion;
}
_client.SendCultNet(new CultNetSnapshotRequestMessage
{
MessageId = messageId,
SchemaIds = CultMesh.CleanSnapshotFilter(options.SchemaIds),
RecordKeys = CultMesh.CleanSnapshotFilter(options.RecordKeys),
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 resolvedSchemas = schemaIds ?? (recordKeys is { Count: > 0 } ? null : new[] { descriptor.SchemaId });
var snapshot = await FetchSnapshotAsync(resolvedSchemas, recordKeys).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)));
_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