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 optional transport connectors. The CultNet schema connector is used by default.
public IReadOnlyList? Connectors { get; set; }
}
///
/// 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 ConcurrentDictionary>> _documents = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary>> _collections = new(StringComparer.Ordinal);
private readonly ConcurrentBag _documentResources = new();
private bool _disposed;
public CultMeshClient(CultMeshClientOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
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 CultMeshSchemaTransportConnector(clock: options.Sessions.Clock)
},
options.Sessions);
}
/// 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 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);
}
/// Opens one live typed document by stable provider identity and record key.
public async Task> DocumentAsync(
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();
var lazy = _documents.GetOrAdd(key, _ => new Lazy>(
async () => await OpenDocumentAsync(endpointId.Trim(), recordKey.Trim()).ConfigureAwait(false),
LazyThreadSafetyMode.ExecutionAndPublication));
try
{
var binding = (RemoteDocumentBinding)await AwaitForCallerAsync(lazy.Value, cancellationToken)
.ConfigureAwait(false);
return binding.Handle;
}
catch
{
_documents.TryRemove(key, out _);
throw;
}
}
/// Opens a live collection of one typed schema by stable provider identity.
public async Task> CollectionAsync(
string endpointId,
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;
var lazy = _collections.GetOrAdd(key, _ => new Lazy>(
async () => await OpenCollectionAsync(identity).ConfigureAwait(false),
LazyThreadSafetyMode.ExecutionAndPublication));
try
{
var binding = (RemoteCollectionBinding)await AwaitForCallerAsync(lazy.Value, cancellationToken)
.ConfigureAwait(false);
return binding.Handle;
}
catch
{
_collections.TryRemove(key, out _);
throw;
}
}
/// 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 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
{
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),
new CultMeshSnapshotRequestOptions(),
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 _documentResources) resource.Dispose();
_documents.Clear();
_collections.Clear();
_sessions.Dispose();
_discovery.Dispose();
}
private void ThrowIfDisposed()
{
if (_disposed) throw new ObjectDisposedException(nameof(CultMeshClient));
}
private async Task