using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GameCult.Caching;
using GameCult.Networking;
using R3;
namespace GameCult.Mesh
{
/// Configures one application-lifetime CultMesh client.
public sealed class CultMeshClientOptions
{
/// Gets or sets the rendezvous endpoints used to bootstrap stable identities.
public IReadOnlyList RendezvousEndpoints { get; set; } = Array.Empty();
/// Gets or sets Verse discovery transport and persistence options.
public CultMeshVerseDiscoveryClientOptions Discovery { get; set; } = new();
/// Gets or sets session path and diagnostic policy.
public CultMeshSessionManagerOptions Sessions { get; set; } = new();
/// Gets or sets schema connectors. Length-prefixed TCP is used by default.
public IReadOnlyList? Connectors { get; set; }
///
/// Gets or sets streaming content connectors. TCP content delivery is used by default;
/// applications may replace it or explicitly add legacy RUDP.
///
public IReadOnlyList? ContentConnectors { get; set; }
///
/// Gets or sets realtime state connectors. No connector is installed implicitly;
/// promoted runtimes should register QUIC and may explicitly add a legacy fallback.
///
public IReadOnlyList RealtimeConnectors { get; set; } =
Array.Empty();
/// Gets or sets the deadline before an unanswered subscription intent is replayed.
public TimeSpan SubscriptionResponseTimeout { get; set; } = TimeSpan.FromSeconds(2);
}
/// Owns one shared live document subscription until disposed.
public sealed class CultMeshDocumentLease : IDisposable where TDocument : class
{
private Action? _release;
internal CultMeshDocumentLease(CultMeshDocumentHandle handle, Action release)
{
Handle = handle ?? throw new ArgumentNullException(nameof(handle));
_release = release ?? throw new ArgumentNullException(nameof(release));
}
/// Gets the live typed document handle owned by this lease.
public CultMeshDocumentHandle Handle { get; }
public void Dispose() => Interlocked.Exchange(ref _release, null)?.Invoke();
}
/// Owns one shared live collection subscription until disposed.
public sealed class CultMeshCollectionLease : IDisposable where TDocument : class
{
private Action? _release;
internal CultMeshCollectionLease(CultMeshCollectionHandle handle, Action release)
{
Handle = handle ?? throw new ArgumentNullException(nameof(handle));
_release = release ?? throw new ArgumentNullException(nameof(release));
}
/// Gets the live typed collection handle owned by this lease.
public CultMeshCollectionHandle Handle { get; }
public void Dispose() => Interlocked.Exchange(ref _release, null)?.Invoke();
}
///
/// Owns discovery and reusable sessions for one application lifetime.
/// Applications address stable identities; CultMesh owns physical routes and reconnection.
///
public sealed class CultMeshClient : IDisposable
{
private readonly CultMeshDiscoveryService _discovery;
private readonly CultMeshSessionManager _sessions;
private readonly TimeSpan _subscriptionResponseTimeout;
private readonly ConcurrentDictionary _documents = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary _collections = new(StringComparer.Ordinal);
private bool _disposed;
public CultMeshClient(CultMeshClientOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
if (options.SubscriptionResponseTimeout <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(options.SubscriptionResponseTimeout));
var endpoints = options.RendezvousEndpoints
.Where(endpoint => !string.IsNullOrWhiteSpace(endpoint))
.Distinct(StringComparer.Ordinal)
.ToArray();
if (endpoints.Length == 0)
throw new ArgumentException("At least one CultMesh rendezvous endpoint is required.", nameof(options));
var discoveryClient = new CultMeshVerseDiscoveryClient(options.Discovery);
_discovery = new CultMeshDiscoveryService(
endpoints.Select(endpoint => new RendezvousLookupSource(endpoint, discoveryClient, options.Discovery)),
new CultMeshDiscoveryServiceOptions
{
Clock = options.Discovery.Clock,
Diagnostics = options.Discovery.Diagnostics,
Store = options.Discovery.DiscoveryStore
});
_sessions = new CultMeshSessionManager(
_discovery,
options.Connectors ?? new ICultMeshTransportConnector[]
{
new CultMeshTcpSchemaTransportConnector(clock: options.Sessions.Clock)
},
options.ContentConnectors ?? new ICultMeshContentTransportConnector[]
{
new CultMeshTcpContentTransportConnector()
},
options.RealtimeConnectors,
options.Sessions);
_subscriptionResponseTimeout = options.SubscriptionResponseTimeout;
}
/// Connects to a stable endpoint identity using one application protocol.
public Task ConnectAsync(
string endpointId,
CultMeshProtocolId protocol,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
return _sessions.ConnectAsync(CultMeshEndpointId.Parse(endpointId), protocol, cancellationToken);
}
/// Connects the reusable realtime state plane by stable endpoint identity.
public Task ConnectRealtimeAsync(
string endpointId,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
return _sessions.ConnectRealtimeAsync(CultMeshEndpointId.Parse(endpointId), cancellationToken);
}
/// Connects to a stable endpoint identity using one application protocol.
public Task ConnectAsync(
CultMeshEndpointId endpointId,
CultMeshProtocolId protocol,
CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
return _sessions.ConnectAsync(endpointId, protocol, cancellationToken);
}
/// Creates a verified-transfer provider over this client's reusable content session owner.
public CultMeshSessionContentProvider ContentProvider(
string providerId,
string endpointId)
{
ThrowIfDisposed();
return new CultMeshSessionContentProvider(
providerId,
_sessions,
CultMeshEndpointId.Parse(endpointId));
}
/// Creates a direct body provider over this client's reusable negotiated session owner.
public CultMeshSessionBodyProvider BodyProvider(
string providerId,
string endpointId,
CultMeshSessionBodyProviderOptions? options = null)
{
ThrowIfDisposed();
return new CultMeshSessionBodyProvider(
providerId,
_sessions,
CultMeshEndpointId.Parse(endpointId),
options);
}
/// Leases one shared live typed document by stable provider identity and record key.
public async Task> LeaseDocumentAsync(
string endpointId,
string recordKey,
CancellationToken cancellationToken = default)
where TDocument : class
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Record key is required.", nameof(recordKey));
var key = endpointId.Trim() + "\u001f" + typeof(TDocument).AssemblyQualifiedName + "\u001f" + recordKey.Trim();
while (true)
{
var resource = _documents.GetOrAdd(key, _ => new SharedResource(
async owner => await OpenDocumentAsync(endpointId.Trim(), recordKey.Trim(), owner).ConfigureAwait(false)));
if (!resource.TryAcquire())
{
RemoveExact(_documents, key, resource);
continue;
}
try
{
var binding = (RemoteDocumentBinding)await AwaitForCallerAsync(resource.Value, cancellationToken)
.ConfigureAwait(false);
return new CultMeshDocumentLease(
binding.Handle,
() => Release(_documents, key, resource));
}
catch
{
Release(_documents, key, resource);
throw;
}
}
}
/// Leases a shared live collection of one typed schema by stable provider identity.
public Task> LeaseCollectionAsync(
string endpointId,
CancellationToken cancellationToken)
where TDocument : class =>
LeaseCollectionAsync(endpointId, includeInitialSnapshot: true, cancellationToken);
/// Leases a live collection and optionally skips replaying its initial snapshot.
public async Task> LeaseCollectionAsync(
string endpointId,
bool includeInitialSnapshot = true,
CancellationToken cancellationToken = default)
where TDocument : class
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
var identity = endpointId.Trim();
var key = identity + "\u001f" + typeof(TDocument).AssemblyQualifiedName + "\u001f" + includeInitialSnapshot;
while (true)
{
var resource = _collections.GetOrAdd(key, _ => new SharedResource(
async owner => await OpenCollectionAsync(identity, includeInitialSnapshot, owner).ConfigureAwait(false)));
if (!resource.TryAcquire())
{
RemoveExact(_collections, key, resource);
continue;
}
try
{
var binding = (RemoteCollectionBinding)await AwaitForCallerAsync(resource.Value, cancellationToken)
.ConfigureAwait(false);
return new CultMeshCollectionLease(
binding.Handle,
() => Release(_collections, key, resource));
}
catch
{
Release(_collections, key, resource);
throw;
}
}
}
///
/// Submits one typed document to a provider by stable identity. Submission is uncommitted input;
/// only a provider-authored receipt or resulting state can establish acceptance.
///
public async Task SubmitDocumentAsync(
string endpointId,
string recordKey,
TDocument document,
string sourceRuntimeId,
string sourceRole,
CancellationToken cancellationToken = default)
where TDocument : class
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Record key is required.", nameof(recordKey));
if (document == null) throw new ArgumentNullException(nameof(document));
if (string.IsNullOrWhiteSpace(sourceRuntimeId)) throw new ArgumentException("Source runtime identity is required.", nameof(sourceRuntimeId));
if (string.IsNullOrWhiteSpace(sourceRole)) throw new ArgumentException("Source role is required.", nameof(sourceRole));
var cacheRegistry = CultMesh.CreateCultCacheDocumentRegistry(typeof(TDocument));
var networkRegistry = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(TDocument) }, cacheRegistry);
var message = networkRegistry.CreateRawDocumentPutMessage(
"cultmesh-client-submit-" + Guid.NewGuid().ToString("N"),
new CultRecordHandle(new CultRecordKey(recordKey.Trim())),
document,
new CultNetDocumentMessageOptions
{
SourceRuntimeId = sourceRuntimeId.Trim(),
SourceRole = sourceRole.Trim()
});
var session = await ConnectAsync(endpointId.Trim(), CultMeshProtocols.Documents, cancellationToken)
.ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
session.OpenSchemaClient().SendCultNet(message);
}
/// Gets the number of currently leased shared document subscriptions.
public int ActiveDocumentResourceCount => _documents.Count;
/// Gets the number of currently leased shared collection subscriptions.
public int ActiveCollectionResourceCount => _collections.Count;
/// Reads one typed record once through the reusable document session.
public async Task ReadAsync(
string endpointId,
string recordKey,
CancellationToken cancellationToken = default)
where TDocument : class
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
if (string.IsNullOrWhiteSpace(recordKey)) throw new ArgumentException("Record key is required.", nameof(recordKey));
var documents = await ReadManyAsync(endpointId, new[] { recordKey }, cancellationToken)
.ConfigureAwait(false);
return documents.FirstOrDefault()
?? throw new InvalidOperationException(
$"CultMesh endpoint '{endpointId}' did not publish {typeof(TDocument).FullName} record '{recordKey}'.");
}
/// Reads one typed record once with an explicit response deadline.
public async Task ReadAsync(
string endpointId,
string recordKey,
TimeSpan responseTimeout,
CancellationToken cancellationToken = default)
where TDocument : class
{
var documents = await ReadManyCoreAsync(
endpointId,
new[] { recordKey },
responseTimeout,
cancellationToken)
.ConfigureAwait(false);
return documents.FirstOrDefault()
?? throw new InvalidOperationException(
$"CultMesh endpoint '{endpointId}' did not publish {typeof(TDocument).FullName} record '{recordKey}'.");
}
/// Reads typed records once in one request through the reusable document session.
public async Task> ReadManyAsync(
string endpointId,
IReadOnlyList recordKeys,
CancellationToken cancellationToken = default)
where TDocument : class
=> await ReadManyCoreAsync(
endpointId,
recordKeys,
TimeSpan.FromSeconds(10),
cancellationToken)
.ConfigureAwait(false);
private async Task> ReadManyCoreAsync(
string endpointId,
IReadOnlyList recordKeys,
TimeSpan responseTimeout,
CancellationToken cancellationToken)
where TDocument : class
{
ThrowIfDisposed();
if (string.IsNullOrWhiteSpace(endpointId)) throw new ArgumentException("Endpoint identity is required.", nameof(endpointId));
if (recordKeys == null || recordKeys.Count == 0 || recordKeys.Any(string.IsNullOrWhiteSpace))
throw new ArgumentException("At least one non-empty record key is required.", nameof(recordKeys));
var cacheRegistry = CultMesh.CreateCultCacheDocumentRegistry(typeof(TDocument));
var networkRegistry = CultMesh.CreateCultNetDocumentRegistry(new[] { typeof(TDocument) }, cacheRegistry);
using var snapshot = await CultMeshSnapshotSession.ConnectAsync(
_sessions,
CultMeshEndpointId.Parse(endpointId),
CultMeshProtocols.Content,
new CultMeshSnapshotRequestOptions
{
ConnectTimeout = TimeSpan.FromSeconds(5),
ResponseTimeout = responseTimeout,
MessageIdPrefix = "cultmesh-client-read"
},
networkRegistry,
cancellationToken)
.ConfigureAwait(false);
return await snapshot.FetchDocumentsAsync(
recordKeys: recordKeys,
schemaIds: new[] { cacheRegistry.GetRequired().SchemaId })
.ConfigureAwait(false);
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
foreach (var resource in _documents.Values.Concat(_collections.Values).Distinct()) resource.Dispose();
_documents.Clear();
_collections.Clear();
_sessions.Dispose();
_discovery.Dispose();
}
private void ThrowIfDisposed()
{
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshClient));
}
private async Task