using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using GameCult.Networking; using R3; namespace GameCult.Mesh { /// /// Well-known CultMesh peer roles. /// public static class CultMeshPeerRoles { /// Peer can answer discovery requests. public const string Discovery = "discovery"; /// Peer can serve authoritative shard logs. public const string ShardPrimary = "shard-primary"; /// Peer can serve replicated shard logs. public const string ShardReplica = "shard-replica"; /// Peer can serve read traffic. public const string ReadReplica = "read-replica"; /// Peer can observe simulation facts. public const string SimulationObserver = "simulation-observer"; } /// /// Candidate peer contact information for a Verse. /// public sealed class CultMeshPeerCard { /// /// Creates a peer card. /// public CultMeshPeerCard( string peerId, string verseId, IEnumerable endpoints, IEnumerable? roles = null, IEnumerable? shardIds = null, string? region = null, string? authorityLeaseId = null, string? expiresAt = null, string? signature = null) { PeerId = RequireNonEmpty(peerId, nameof(peerId)); VerseId = RequireNonEmpty(verseId, nameof(verseId)); Endpoints = Clean(endpoints); Roles = Clean(roles); ShardIds = Clean(shardIds); Region = region; AuthorityLeaseId = authorityLeaseId; ExpiresAt = expiresAt; Signature = signature; } /// Gets the stable peer id. public string PeerId { get; } /// Gets the Verse id this peer participates in. public string VerseId { get; } /// Gets reachable endpoints. public IReadOnlyList Endpoints { get; } /// Gets advertised roles. public IReadOnlyList Roles { get; } /// Gets shard ids this peer can serve or observe. public IReadOnlyList ShardIds { get; } /// Gets an optional region/locality label. public string? Region { get; } /// Gets the authority lease id, when present. public string? AuthorityLeaseId { get; } /// Gets the expiry timestamp for this card. public string? ExpiresAt { get; } /// Gets an optional signature over the card. public string? Signature { get; } /// /// Returns whether the card advertises a role. /// public bool HasRole(string role) { return Roles.Contains(role, StringComparer.Ordinal); } private static string[] Clean(IEnumerable? values) { return values?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray() ?? Array.Empty(); } private static string RequireNonEmpty(string value, string paramName) { return string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value must be non-empty.", paramName) : value; } } /// /// Conversion helpers for CultMesh peer exchange messages. /// public static class CultMeshPeerMessages { /// /// Converts a peer card to its schema-v0 wire shape. /// public static CultMeshPeerCardMessage ToMessage(this CultMeshPeerCard card) { if (card == null) throw new ArgumentNullException(nameof(card)); return new CultMeshPeerCardMessage { PeerId = card.PeerId, VerseId = card.VerseId, Endpoints = card.Endpoints.ToArray(), Roles = card.Roles.ToArray(), ShardIds = card.ShardIds.ToArray(), Region = card.Region, AuthorityLeaseId = card.AuthorityLeaseId, ExpiresAt = card.ExpiresAt, Signature = card.Signature }; } /// /// Converts a wire peer card to the local public API shape. /// public static CultMeshPeerCard ToPeerCard(this CultMeshPeerCardMessage message) { if (message == null) throw new ArgumentNullException(nameof(message)); return new CultMeshPeerCard( message.PeerId, message.VerseId, message.Endpoints, message.Roles, message.ShardIds, message.Region, message.AuthorityLeaseId, message.ExpiresAt, message.Signature); } } /// /// Reactive local catalog for discovered CultMesh peers. /// public sealed class CultMeshPeerCatalog : IDisposable { private readonly Dictionary _peers = new(StringComparer.Ordinal); private readonly Subject _updates = new(); private bool _disposed; /// Gets all known peers. public IReadOnlyList Peers => _peers.Values.OrderBy(peer => peer.PeerId, StringComparer.Ordinal).ToArray(); /// Watches peer card updates. public Observable Watch() { ThrowIfDisposed(); return _updates; } /// Adds or replaces a peer card. public void Upsert(CultMeshPeerCard card) { ThrowIfDisposed(); if (card == null) throw new ArgumentNullException(nameof(card)); _peers[card.PeerId] = card; _updates.OnNext(card); } /// Adds or replaces peer cards from a wire response. public void Upsert(CultMeshPeerExchangeResponseMessage response) { ThrowIfDisposed(); if (response == null) throw new ArgumentNullException(nameof(response)); foreach (var peer in response.Peers) { Upsert(peer.ToPeerCard()); } } /// Finds peers by Verse and optional role. public IReadOnlyList Find(string verseId, string? role = null) { ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(verseId)) throw new ArgumentException("Value must be non-empty.", nameof(verseId)); return _peers.Values .Where(peer => string.Equals(peer.VerseId, verseId, StringComparison.Ordinal)) .Where(peer => string.IsNullOrWhiteSpace(role) || peer.HasRole(role!)) .OrderBy(peer => peer.PeerId, StringComparer.Ordinal) .ToArray(); } /// Finds peers that advertise a Verse role and are authorized by the supplied lease catalog. public IReadOnlyList FindAuthorized( string verseId, string role, CultMeshAuthorityLeaseCatalog leases, string? shardId = null, DateTimeOffset? at = null) { ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(verseId)) throw new ArgumentException("Value must be non-empty.", nameof(verseId)); if (string.IsNullOrWhiteSpace(role)) throw new ArgumentException("Value must be non-empty.", nameof(role)); if (leases == null) throw new ArgumentNullException(nameof(leases)); return Find(verseId, role) .Where(peer => leases.IsAuthorized(peer, role, shardId, at)) .ToArray(); } /// Returns the first peer that advertises a Verse role and is authorized by the supplied lease catalog. public CultMeshPeerCard? FirstAuthorized( string verseId, string role, CultMeshAuthorityLeaseCatalog leases, string? shardId = null, DateTimeOffset? at = null) { return FindAuthorized(verseId, role, leases, shardId, at).FirstOrDefault(); } /// public void Dispose() { if (_disposed) { return; } _disposed = true; _updates.Dispose(); _peers.Clear(); } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(CultMeshPeerCatalog)); } } } /// /// Answers CultMesh peer exchange requests from a local peer catalog. /// public sealed class CultMeshPeerExchangeServer : IDisposable { private readonly Server _server; private readonly CultMeshPeerCatalog _catalog; private readonly Func _requestHandler; private bool _disposed; /// /// Creates and attaches a peer exchange bridge. /// public CultMeshPeerExchangeServer(Server server, CultMeshPeerCatalog catalog) { _server = server ?? throw new ArgumentNullException(nameof(server)); _catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); _requestHandler = HandleRequestAsync; _server.OnCultNet(_requestHandler); } /// /// Creates a peer exchange response for a request. /// public CultMeshPeerExchangeResponseMessage CreateResponse(CultMeshPeerExchangeRequestMessage request) { if (request == null) throw new ArgumentNullException(nameof(request)); if (string.IsNullOrWhiteSpace(request.VerseId)) { throw new ArgumentException("Peer exchange requires a verseId.", nameof(request)); } var known = request.KnownPeerIds == null || request.KnownPeerIds.Length == 0 ? null : new HashSet(request.KnownPeerIds, StringComparer.Ordinal); var roles = request.Roles == null || request.Roles.Length == 0 ? null : new HashSet(request.Roles, StringComparer.Ordinal); var peers = _catalog.Find(request.VerseId) .Where(peer => known == null || !known.Contains(peer.PeerId)) .Where(peer => roles == null || peer.Roles.Any(role => roles.Contains(role))) .Take(request.Limit ?? int.MaxValue) .Select(peer => peer.ToMessage()) .ToArray(); return new CultMeshPeerExchangeResponseMessage { MessageId = string.IsNullOrWhiteSpace(request.MessageId) ? Guid.NewGuid().ToString("N") : request.MessageId, Peers = peers }; } /// public void Dispose() { if (_disposed) { return; } _disposed = true; _server.RemoveCultNetMessageListener(_requestHandler); } private Task HandleRequestAsync(CultMeshPeerExchangeRequestMessage request, CultNetServerPeer peer) { peer.SendCultNet(CreateResponse(request)); return Task.CompletedTask; } } /// /// Options for schema-v0 CultMesh peer exchange clients. /// public sealed class CultMeshPeerExchangeClientOptions { /// /// Gets or sets client security options used to connect to peer exchange endpoints. /// public ClientSecurityOptions? Security { get; set; } /// /// Gets or sets how long to wait for a connection before failing. /// public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(5); /// /// Gets or sets how long to wait for a peer exchange response before failing. /// public TimeSpan ResponseTimeout { get; set; } = TimeSpan.FromSeconds(5); /// /// Gets or sets a callback used to customize each ephemeral exchange client. /// public Action? ConfigureClient { get; set; } /// /// Gets or sets the schema-v0 client factory. /// Defaults to endpoint selection: rudp:// uses RUDP and cultnet:// uses LiteNetLib. /// public Func? CreateClient { get; set; } /// Gets or sets the shared CultMesh session owner. public CultMeshSessionManager? Sessions { get; set; } /// Gets or sets the clock used by managed response deadlines. public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance; } /// /// Fetches peer cards from CultMesh peers. /// public sealed class CultMeshPeerExchangeClient { private readonly CultMeshPeerExchangeClientOptions _options; /// /// Creates a peer exchange client. /// public CultMeshPeerExchangeClient(CultMeshPeerExchangeClientOptions? options = null) { _options = options ?? new CultMeshPeerExchangeClientOptions(); } /// /// Fetches peer cards from one endpoint. /// public async Task FetchAsync( string endpoint, CultMeshPeerExchangeRequestMessage request) { if (string.IsNullOrWhiteSpace(endpoint)) throw new ArgumentException("Value must be non-empty.", nameof(endpoint)); if (request == null) throw new ArgumentNullException(nameof(request)); if (string.IsNullOrWhiteSpace(request.VerseId)) throw new ArgumentException("Peer exchange requires a verseId.", nameof(request)); var (host, port) = CultNetSchemaWriteForwarder.ParseEndpoint(endpoint); var messageId = Guid.NewGuid().ToString("N"); var completion = new TaskCompletionSource( TaskCreationOptions.RunContinuationsAsynchronously); using var client = CreateClient(endpoint); client.OnCultNet(response => { if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal)) { completion.TrySetResult(response); } }); client.OnCultNet(error => completion.TrySetException(new InvalidOperationException(error.Error))); client.Connect(host, port); await WaitForConnectionAsync(client, endpoint).ConfigureAwait(false); client.SendCultNet(new CultMeshPeerExchangeRequestMessage { MessageId = messageId, VerseId = request.VerseId, Roles = request.Roles, KnownPeerIds = request.KnownPeerIds, Limit = request.Limit }); return await WaitForResponseAsync(completion.Task, endpoint).ConfigureAwait(false); } /// Fetches peer cards through the shared session owner. public async Task FetchAsync( CultMeshEndpointId endpointId, CultMeshPeerExchangeRequestMessage request, CancellationToken cancellationToken = default) { if (endpointId == null) throw new ArgumentNullException(nameof(endpointId)); if (request == null) throw new ArgumentNullException(nameof(request)); if (string.IsNullOrWhiteSpace(request.VerseId)) throw new ArgumentException("Peer exchange requires a verseId.", nameof(request)); var sessions = _options.Sessions ?? throw new InvalidOperationException("Managed peer exchange requires a CultMeshSessionManager."); var session = await sessions.ConnectAsync(endpointId, CultMeshProtocols.PeerExchange, cancellationToken).ConfigureAwait(false); var messageId = Guid.NewGuid().ToString("N"); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); using var responseSubscription = session.OnCultNet(response => { if (string.Equals(response.MessageId, messageId, StringComparison.Ordinal)) completion.TrySetResult(response); }); using var errorSubscription = session.OnCultNet(error => completion.TrySetException(new InvalidOperationException(error.Error))); session.SendCultNet(new CultMeshPeerExchangeRequestMessage { MessageId = messageId, VerseId = request.VerseId, Roles = request.Roles, KnownPeerIds = request.KnownPeerIds, Limit = request.Limit }); return await WaitForManagedResponseAsync(completion.Task, endpointId, cancellationToken).ConfigureAwait(false); } /// /// Fetches peer cards from endpoints and upserts every response into a local peer catalog. /// public async Task DiscoverAsync( CultMeshPeerCatalog catalog, IEnumerable endpoints, string verseId, IEnumerable? roles = null, int? limit = null) { if (catalog == null) throw new ArgumentNullException(nameof(catalog)); if (endpoints == null) throw new ArgumentNullException(nameof(endpoints)); if (string.IsNullOrWhiteSpace(verseId)) throw new ArgumentException("Value must be non-empty.", nameof(verseId)); var count = 0; foreach (var endpoint in endpoints.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal)) { var response = await FetchAsync(endpoint, new CultMeshPeerExchangeRequestMessage { VerseId = verseId, Roles = roles?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray(), KnownPeerIds = catalog.Find(verseId).Select(peer => peer.PeerId).ToArray(), Limit = limit }).ConfigureAwait(false); catalog.Upsert(response); count += response.Peers.Length; } return count; } private ICultNetSchemaClient CreateClient(string endpoint) { return _options.CreateClient?.Invoke() ?? CultNetSchemaClients.CreateForEndpoint(endpoint, _options.Security, _options.ConfigureClient); } private async Task WaitForConnectionAsync(ICultNetSchemaClient client, string endpoint) { var deadline = DateTimeOffset.UtcNow + _options.ConnectTimeout; while (!client.Connected) { if (DateTimeOffset.UtcNow >= deadline) { throw new TimeoutException($"Timed out connecting to peer exchange endpoint {endpoint}."); } await Task.Delay(TimeSpan.FromMilliseconds(25)).ConfigureAwait(false); } } private async Task WaitForResponseAsync( Task responseTask, string endpoint) { 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 peer exchange response from {endpoint}."); } return await responseTask.ConfigureAwait(false); } private async Task WaitForManagedResponseAsync( Task responseTask, CultMeshEndpointId endpointId, CancellationToken cancellationToken) { var timeout = _options.Clock.DelayAsync(_options.ResponseTimeout, cancellationToken); var completed = await Task.WhenAny(responseTask, timeout).ConfigureAwait(false); if (completed != responseTask) { cancellationToken.ThrowIfCancellationRequested(); throw new TimeoutException($"Timed out waiting for peer exchange response from {endpointId}."); } return await responseTask.ConfigureAwait(false); } } }