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; } } /// /// 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) { VerseId = RequireNonEmpty(verseId, nameof(verseId)); DisplayName = RequireNonEmpty(displayName, nameof(displayName)); AuthorityModel = authorityModel; Compatibility = compatibility ?? throw new ArgumentNullException(nameof(compatibility)); DiscoveryEndpoints = Clean(discoveryEndpoints); AuthorityRuntimeIds = Clean(authorityRuntimeIds); 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 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)).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; } } /// /// 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)); } } } }