using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using GameCult.Networking; using R3; namespace GameCult.Mesh { /// /// Describes how a CultMesh Verse makes authority decisions. /// public enum CultMeshVerseAuthorityModel { /// /// A known operator cluster is authoritative for committed world state. /// OperatorCluster, /// /// Regional operators share authority for lower latency and availability. /// FederatedCluster, /// /// Peers participate directly in authority decisions. /// PeerToPeer, /// /// The Verse follows another Verse and applies declared overlays. /// SubscribedOverlay } /// /// Declares transport and rules compatibility for a Verse. /// public sealed class CultMeshVerseCompatibility { /// /// Creates compatibility metadata. /// public CultMeshVerseCompatibility( string transportVersion, string rulesHash, IEnumerable? compatibleVerseIds = null, IEnumerable? requiredPluginIds = null, IEnumerable? optionalPluginIds = null) { TransportVersion = RequireNonEmpty(transportVersion, nameof(transportVersion)); RulesHash = RequireNonEmpty(rulesHash, nameof(rulesHash)); CompatibleVerseIds = Clean(compatibleVerseIds); RequiredPluginIds = Clean(requiredPluginIds); OptionalPluginIds = Clean(optionalPluginIds); } /// /// Gets the CultMesh/CultNet transport compatibility version. /// public string TransportVersion { get; } /// /// Gets the stable rules hash. /// public string RulesHash { get; } /// /// Gets Verse ids this Verse can transfer from or subscribe to. /// public IReadOnlyList CompatibleVerseIds { get; } /// /// Gets plugin ids required to enter this Verse. /// public IReadOnlyList RequiredPluginIds { get; } /// /// Gets plugin ids supported but not required by this Verse. /// public IReadOnlyList OptionalPluginIds { get; } 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) { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Value must be non-empty.", paramName); } return value; } } /// /// Binds one authoritative runtime to one physical route. This relationship is /// the routing authority; the legacy endpoint/runtime lists are projections only. /// public sealed class CultMeshAuthorityRoute { public CultMeshAuthorityRoute( string authorityRuntimeId, string endpoint, IEnumerable? protocolIds = null, int priority = 0, string? generation = null, CultMeshRouteCertificate? certificate = null) { AuthorityRuntimeId = RequireNonEmpty(authorityRuntimeId, nameof(authorityRuntimeId)); Endpoint = RequireNonEmpty(endpoint, nameof(endpoint)); ProtocolIds = Clean(protocolIds); if (priority < 0) throw new ArgumentOutOfRangeException(nameof(priority)); Priority = priority; Generation = string.IsNullOrWhiteSpace(generation) ? AuthorityRuntimeId + "@" + Endpoint : generation!.Trim(); Certificate = certificate; } public string AuthorityRuntimeId { get; } public string Endpoint { get; } public IReadOnlyList ProtocolIds { get; } public int Priority { get; } public string Generation { get; } /// Gets the optional Odin-signed binding from this route to its provider key. public CultMeshRouteCertificate? Certificate { get; } public bool Supports(CultMeshProtocolId protocol) => protocol != null && (ProtocolIds.Count == 0 || ProtocolIds.Contains(protocol.Value, StringComparer.Ordinal)); private static string[] Clean(IEnumerable? values) => values?.Where(value => !string.IsNullOrWhiteSpace(value)) .Select(value => value.Trim()) .Distinct(StringComparer.Ordinal) .OrderBy(value => value, StringComparer.Ordinal) .ToArray() ?? Array.Empty(); private static string RequireNonEmpty(string value, string paramName) => string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value must be non-empty.", paramName) : value.Trim(); } /// /// Describes one CultMesh Verse: a rule-bearing consensus graph. /// public sealed class CultMeshVerseDescriptor { /// /// Creates a Verse descriptor. /// public CultMeshVerseDescriptor( string verseId, string displayName, CultMeshVerseAuthorityModel authorityModel, CultMeshVerseCompatibility compatibility, IEnumerable? discoveryEndpoints = null, IEnumerable? authorityRuntimeIds = null, string? parentVerseId = null, string? description = null, IEnumerable? authorityRoutes = null) { VerseId = RequireNonEmpty(verseId, nameof(verseId)); DisplayName = RequireNonEmpty(displayName, nameof(displayName)); AuthorityModel = authorityModel; Compatibility = compatibility ?? throw new ArgumentNullException(nameof(compatibility)); var legacyEndpoints = Clean(discoveryEndpoints); var legacyRuntimeIds = Clean(authorityRuntimeIds); var suppliedRoutes = authorityRoutes?.ToArray(); if (suppliedRoutes?.Any(route => route == null) == true) throw new ArgumentException("Authority routes cannot contain null.", nameof(authorityRoutes)); if (suppliedRoutes != null && (legacyEndpoints.Length > 0 || legacyRuntimeIds.Length > 0)) throw new ArgumentException( "Supply bound authority routes or legacy endpoint/runtime lists, never both.", nameof(authorityRoutes)); if (suppliedRoutes == null && legacyEndpoints.Length > 0 && legacyRuntimeIds.Length > 1) throw new InvalidOperationException( "Legacy Verse routing with multiple authority runtimes is ambiguous. " + "Publish explicit CultMeshAuthorityRoute bindings."); AuthorityRoutes = NormalizeRoutes(suppliedRoutes ?? (legacyRuntimeIds.Length == 1 ? legacyEndpoints.Select(endpoint => new CultMeshAuthorityRoute(legacyRuntimeIds[0], endpoint)) : Array.Empty())); DiscoveryEndpoints = AuthorityRoutes.Count > 0 ? AuthorityRoutes.Select(route => route.Endpoint).Distinct(StringComparer.Ordinal).ToArray() : legacyEndpoints; AuthorityRuntimeIds = AuthorityRoutes.Select(route => route.AuthorityRuntimeId) .Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray(); ParentVerseId = parentVerseId; Description = description; } /// /// Gets the stable Verse id. /// public string VerseId { get; } /// /// Gets the human-facing Verse name. /// public string DisplayName { get; } /// /// Gets the authority model used by this Verse. /// public CultMeshVerseAuthorityModel AuthorityModel { get; } /// /// Gets compatibility metadata for transport, rules, and plugins. /// public CultMeshVerseCompatibility Compatibility { get; } /// /// Gets discovery endpoints for nodes serving this Verse. /// public IReadOnlyList DiscoveryEndpoints { get; } /// /// Gets known authoritative runtime ids, when authority is cluster-shaped. /// public IReadOnlyList AuthorityRuntimeIds { get; } /// Gets exact authority-to-route bindings used for identity-sensitive resolution. public IReadOnlyList AuthorityRoutes { get; } /// /// Gets the parent Verse id for subscribed overlays or branches. /// public string? ParentVerseId { get; } /// /// Gets optional public description. /// public string? Description { get; } /// /// Returns whether this Verse can accept transfer from another Verse. /// public bool CanTransferFrom(CultMeshVerseDescriptor source) { if (source == null) throw new ArgumentNullException(nameof(source)); return string.Equals(Compatibility.TransportVersion, source.Compatibility.TransportVersion, StringComparison.Ordinal) && (string.Equals(Compatibility.RulesHash, source.Compatibility.RulesHash, StringComparison.Ordinal) || Compatibility.CompatibleVerseIds.Contains(source.VerseId, StringComparer.Ordinal)); } /// /// Computes a stable rules hash from ordered rules/plugin parts. /// public static string ComputeRulesHash(params string[] parts) { if (parts == null) throw new ArgumentNullException(nameof(parts)); var canonical = string.Join("\u001F", parts.Select(part => part ?? string.Empty)); using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(canonical)); return string.Concat(bytes.Select(value => value.ToString("x2"))); } private static string[] Clean(IEnumerable? values) { return values?.Where(value => !string.IsNullOrWhiteSpace(value)) .Select(value => value.Trim()) .Distinct(StringComparer.Ordinal) .ToArray() ?? Array.Empty(); } private static CultMeshAuthorityRoute[] NormalizeRoutes(IEnumerable routes) { return routes .GroupBy(route => new { route.AuthorityRuntimeId, route.Endpoint, Protocols = string.Join("\u001f", route.ProtocolIds) }) .Select(group => group.OrderBy(route => route.Priority).First()) .OrderBy(route => route.Priority) .ThenBy(route => route.AuthorityRuntimeId, StringComparer.Ordinal) .ThenBy(route => route.Endpoint, StringComparer.Ordinal) .ToArray(); } private static string RequireNonEmpty(string value, string paramName) { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Value must be non-empty.", paramName); } return value; } } /// /// Reactive local catalog for discovered CultMesh Verses. /// public sealed class CultMeshVerseCatalog : IDisposable { private readonly Dictionary _verses = new(StringComparer.Ordinal); private readonly Subject _updates = new(); private bool _disposed; /// /// Gets all known Verses. /// public IReadOnlyList Verses => _verses.Values.OrderBy(verse => verse.VerseId, StringComparer.Ordinal).ToArray(); /// /// Watches Verse discovery updates. /// public Observable Watch() { ThrowIfDisposed(); return _updates; } /// /// Adds or replaces a discovered Verse. /// public void Upsert(CultMeshVerseDescriptor verse) { ThrowIfDisposed(); if (verse == null) throw new ArgumentNullException(nameof(verse)); _verses[verse.VerseId] = verse; _updates.OnNext(verse); } /// /// Adds or replaces Verses from a wire catalog response. /// public void Upsert(CultMeshVerseCatalogResponseMessage response) { ThrowIfDisposed(); if (response == null) throw new ArgumentNullException(nameof(response)); foreach (var verse in response.Verses) { Upsert(verse.ToVerseDescriptor()); } } /// /// Gets a Verse by id, if known. /// public CultMeshVerseDescriptor? Get(string verseId) { ThrowIfDisposed(); if (string.IsNullOrWhiteSpace(verseId)) throw new ArgumentException("Value must be non-empty.", nameof(verseId)); return _verses.TryGetValue(verseId, out var verse) ? verse : null; } /// /// Gets known Verses that can accept transfer from the supplied source Verse. /// public IReadOnlyList FindTransferTargets(CultMeshVerseDescriptor source) { ThrowIfDisposed(); if (source == null) throw new ArgumentNullException(nameof(source)); return _verses.Values .Where(verse => !string.Equals(verse.VerseId, source.VerseId, StringComparison.Ordinal) && verse.CanTransferFrom(source)) .OrderBy(verse => verse.VerseId, StringComparer.Ordinal) .ToArray(); } /// public void Dispose() { if (_disposed) { return; } _disposed = true; _updates.Dispose(); _verses.Clear(); } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(CultMeshVerseCatalog)); } } } }