diff --git a/src/GameCult.Mesh/CultMeshDiscoveryService.cs b/src/GameCult.Mesh/CultMeshDiscoveryService.cs new file mode 100644 index 00000000..964477e3 --- /dev/null +++ b/src/GameCult.Mesh/CultMeshDiscoveryService.cs @@ -0,0 +1,461 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameCult.Caching; +using GameCult.Networking; +using MessagePack; +using R3; + +namespace GameCult.Mesh +{ + public static class CultMeshDiscoverySchemaVersions + { + public const string State = "gamecult.mesh.discovery_state.v1"; + } + + public enum CultMeshDiscoveryFreshness + { + Fresh, + Degraded, + Stale, + Unavailable + } + + public enum CultMeshDiscoveryTrust + { + Rejected, + Unsigned, + Signed + } + + public sealed class CultMeshDiscoveryQuery + { + public CultMeshDiscoveryQuery(string endpointId, IEnumerable? verseIds = null) + { + EndpointId = Require(endpointId, nameof(endpointId)); + VerseIds = verseIds?.Where(value => !string.IsNullOrWhiteSpace(value)) + .Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray() + ?? Array.Empty(); + } + + public string EndpointId { get; } + public IReadOnlyList VerseIds { get; } + + private static string Require(string value, string name) => + string.IsNullOrWhiteSpace(value) ? throw new ArgumentException("Value must be non-empty.", name) : value; + } + + public sealed class CultMeshDiscoveryObservation + { + public CultMeshDiscoveryObservation( + CultMeshVerseDescriptor candidate, + string sourceId, + DateTimeOffset observedAtUtc, + DateTimeOffset expiresAtUtc, + CultMeshDiscoveryTrust trust = CultMeshDiscoveryTrust.Unsigned, + string evidence = "") + { + Candidate = candidate ?? throw new ArgumentNullException(nameof(candidate)); + SourceId = string.IsNullOrWhiteSpace(sourceId) + ? throw new ArgumentException("Value must be non-empty.", nameof(sourceId)) + : sourceId; + if (expiresAtUtc < observedAtUtc) throw new ArgumentOutOfRangeException(nameof(expiresAtUtc)); + ObservedAtUtc = observedAtUtc; + ExpiresAtUtc = expiresAtUtc; + Trust = trust; + Evidence = evidence ?? ""; + } + + public CultMeshVerseDescriptor Candidate { get; } + public string SourceId { get; } + public DateTimeOffset ObservedAtUtc { get; } + public DateTimeOffset ExpiresAtUtc { get; } + public CultMeshDiscoveryTrust Trust { get; } + public string Evidence { get; } + } + + public interface ICultMeshLookupSource + { + string SourceId { get; } + + Task> LookupAsync( + CultMeshDiscoveryQuery query, + CancellationToken cancellationToken = default); + } + + public interface ICultMeshDiscoveryStore + { + Task LoadAsync(string endpointId, CancellationToken cancellationToken = default); + + Task SaveAsync(CultMeshDiscoveryState state, CancellationToken cancellationToken = default); + } + + public sealed class CultMeshDiscoveryCandidate + { + public CultMeshDiscoveryCandidate( + CultMeshVerseDescriptor descriptor, + string sourceId, + DateTimeOffset observedAtUtc, + DateTimeOffset expiresAtUtc, + CultMeshDiscoveryTrust trust) + { + Descriptor = descriptor ?? throw new ArgumentNullException(nameof(descriptor)); + SourceId = sourceId ?? ""; + ObservedAtUtc = observedAtUtc; + ExpiresAtUtc = expiresAtUtc; + Trust = trust; + } + + public CultMeshVerseDescriptor Descriptor { get; } + public string SourceId { get; } + public DateTimeOffset ObservedAtUtc { get; } + public DateTimeOffset ExpiresAtUtc { get; } + public CultMeshDiscoveryTrust Trust { get; } + } + + public sealed class CultMeshDiscoveryState + { + public CultMeshDiscoveryState( + string endpointId, + CultMeshDiscoveryFreshness freshness, + IEnumerable? candidates, + DateTimeOffset evaluatedAtUtc, + DateTimeOffset? retryAfterUtc = null, + IEnumerable? failedSourceIds = null, + string? queryKey = null) + { + EndpointId = endpointId ?? ""; + Freshness = freshness; + Candidates = candidates?.OrderBy(candidate => candidate.Descriptor.VerseId, StringComparer.Ordinal).ToArray() + ?? Array.Empty(); + EvaluatedAtUtc = evaluatedAtUtc; + RetryAfterUtc = retryAfterUtc; + FailedSourceIds = failedSourceIds?.Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray() + ?? Array.Empty(); + QueryKey = string.IsNullOrWhiteSpace(queryKey) ? EndpointId : queryKey; + } + + public string EndpointId { get; } + public CultMeshDiscoveryFreshness Freshness { get; } + public IReadOnlyList Candidates { get; } + public DateTimeOffset EvaluatedAtUtc { get; } + public DateTimeOffset? RetryAfterUtc { get; } + public IReadOnlyList FailedSourceIds { get; } + public string QueryKey { get; } + } + + public sealed class CultMeshDiscoveryServiceOptions + { + public ICultMeshClock Clock { get; set; } = CultMeshSystemClock.Instance; + public ICultMeshDiagnosticSink Diagnostics { get; set; } = CultMeshNullDiagnosticSink.Instance; + public ICultMeshDiscoveryStore? Store { get; set; } + public TimeSpan NegativeTtl { get; set; } = TimeSpan.FromSeconds(30); + } + + public sealed class CultMeshDiscoveryService : IDisposable + { + private readonly ICultMeshLookupSource[] _sources; + private readonly CultMeshDiscoveryServiceOptions _options; + private readonly ConcurrentDictionary>> _inFlight = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _states = new(StringComparer.Ordinal); + private readonly Subject _updates = new(); + private long _diagnosticSequence; + private bool _disposed; + + public CultMeshDiscoveryService( + IEnumerable sources, + CultMeshDiscoveryServiceOptions? options = null) + { + _sources = sources?.ToArray() ?? throw new ArgumentNullException(nameof(sources)); + if (_sources.Any(source => source == null)) throw new ArgumentException("Lookup sources cannot contain null.", nameof(sources)); + _options = options ?? new CultMeshDiscoveryServiceOptions(); + if (_options.NegativeTtl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(options)); + } + + public Observable Watch() => _updates; + + public CultMeshDiscoveryState? Current(string endpointId) + { + _states.TryGetValue(endpointId, out var state); + return state == null ? null : EvaluateAt(state, _options.Clock.UtcNow); + } + + public async Task ResolveAsync( + CultMeshDiscoveryQuery query, + CancellationToken cancellationToken = default) + { + if (query == null) throw new ArgumentNullException(nameof(query)); + ThrowIfDisposed(); + var lookupKey = QueryKey(query); + var lazy = _inFlight.GetOrAdd( + lookupKey, + _ => new Lazy>( + () => ResolveOwnedAsync(query, CancellationToken.None), + LazyThreadSafetyMode.ExecutionAndPublication)); + var shared = lazy.Value; + _ = shared.ContinueWith( + completed => _inFlight.TryRemove(lookupKey, out _), + CancellationToken.None, + TaskContinuationOptions.ExecuteSynchronously, + TaskScheduler.Default); + return await AwaitForCallerAsync(shared, cancellationToken).ConfigureAwait(false); + } + + private static string QueryKey(CultMeshDiscoveryQuery query) => + query.VerseIds.Count == 0 + ? query.EndpointId + : query.EndpointId + "\u001f" + string.Join("\u001f", query.VerseIds); + + private static async Task AwaitForCallerAsync(Task shared, CancellationToken cancellationToken) + { + if (!cancellationToken.CanBeCanceled) + return await shared.ConfigureAwait(false); + var cancelled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using (cancellationToken.Register(() => cancelled.TrySetResult(true))) + { + if (await Task.WhenAny(shared, cancelled.Task).ConfigureAwait(false) != shared) + throw new OperationCanceledException(cancellationToken); + } + return await shared.ConfigureAwait(false); + } + + private async Task ResolveOwnedAsync( + CultMeshDiscoveryQuery query, + CancellationToken cancellationToken) + { + var queryKey = QueryKey(query); + var previous = await LoadPreviousAsync(queryKey, cancellationToken).ConfigureAwait(false); + var now = _options.Clock.UtcNow; + if (previous != null && + ((previous.Freshness == CultMeshDiscoveryFreshness.Fresh && + previous.Candidates.Count > 0 && previous.Candidates.All(candidate => candidate.ExpiresAtUtc > now)) || + (previous.Freshness == CultMeshDiscoveryFreshness.Unavailable && previous.RetryAfterUtc > now))) + { + return previous; + } + var lookups = _sources.Select(source => ObserveSourceAsync(source, query, cancellationToken)).ToArray(); + var results = await Task.WhenAll(lookups).ConfigureAwait(false); + var failures = results.Where(result => result.Error != null).Select(result => result.SourceId).ToArray(); + var observations = results.SelectMany(result => result.Observations) + .Where(observation => query.VerseIds.Count == 0 || query.VerseIds.Contains(observation.Candidate.VerseId, StringComparer.Ordinal)) + .ToArray(); + + foreach (var rejected in observations.Where(observation => observation.Trust == CultMeshDiscoveryTrust.Rejected)) + { + Emit(CultMeshDiagnosticKind.CandidateRejected, query.EndpointId, rejected.Candidate.VerseId, + "rejected", "trust_rejected", rejected.SourceId); + } + + var accepted = observations.Where(observation => observation.Trust != CultMeshDiscoveryTrust.Rejected) + .GroupBy(observation => observation.Candidate.VerseId, StringComparer.Ordinal) + .Select(group => group + .OrderByDescending(observation => observation.Trust) + .ThenByDescending(observation => observation.ObservedAtUtc) + .First()) + .Select(observation => new CultMeshDiscoveryCandidate( + observation.Candidate, + observation.SourceId, + observation.ObservedAtUtc, + observation.ExpiresAtUtc, + observation.Trust)) + .ToArray(); + + IReadOnlyList candidates = accepted.Length > 0 + ? accepted + : previous?.Candidates ?? Array.Empty(); + var freshCount = candidates.Count(candidate => candidate.ExpiresAtUtc > now); + CultMeshDiscoveryFreshness freshness; + if (accepted.Length > 0) + freshness = freshCount == 0 + ? CultMeshDiscoveryFreshness.Stale + : failures.Length > 0 || freshCount < candidates.Count + ? CultMeshDiscoveryFreshness.Degraded + : CultMeshDiscoveryFreshness.Fresh; + else if (candidates.Count > 0) + freshness = freshCount > 0 ? CultMeshDiscoveryFreshness.Degraded : CultMeshDiscoveryFreshness.Stale; + else + freshness = CultMeshDiscoveryFreshness.Unavailable; + + var state = new CultMeshDiscoveryState( + query.EndpointId, + freshness, + candidates, + now, + freshness == CultMeshDiscoveryFreshness.Fresh ? null : now + _options.NegativeTtl, + failures, + queryKey); + _states[queryKey] = state; + if (_options.Store != null) await _options.Store.SaveAsync(state, cancellationToken).ConfigureAwait(false); + _updates.OnNext(state); + Emit(CultMeshDiagnosticKind.DiscoveryObservation, query.EndpointId, query.EndpointId, + freshness.ToString().ToLowerInvariant(), failures.Length == 0 ? "" : "source_failure", "discovery-service"); + return state; + } + + private static CultMeshDiscoveryState EvaluateAt(CultMeshDiscoveryState state, DateTimeOffset now) + { + if (state.Candidates.Count == 0 || state.Freshness == CultMeshDiscoveryFreshness.Unavailable) + return state; + var freshCount = state.Candidates.Count(candidate => candidate.ExpiresAtUtc > now); + var freshness = freshCount == 0 + ? CultMeshDiscoveryFreshness.Stale + : freshCount < state.Candidates.Count || state.FailedSourceIds.Count > 0 + ? CultMeshDiscoveryFreshness.Degraded + : CultMeshDiscoveryFreshness.Fresh; + return freshness == state.Freshness + ? state + : new CultMeshDiscoveryState( + state.EndpointId, freshness, state.Candidates, now, + state.RetryAfterUtc, state.FailedSourceIds, state.QueryKey); + } + + private async Task LoadPreviousAsync(string queryKey, CancellationToken cancellationToken) + { + if (_states.TryGetValue(queryKey, out var current)) return current; + if (_options.Store == null) return null; + var stored = await _options.Store.LoadAsync(queryKey, cancellationToken).ConfigureAwait(false); + if (stored != null) _states[queryKey] = stored; + return stored; + } + + private static async Task ObserveSourceAsync( + ICultMeshLookupSource source, + CultMeshDiscoveryQuery query, + CancellationToken cancellationToken) + { + try + { + var observations = await source.LookupAsync(query, cancellationToken).ConfigureAwait(false); + return new LookupResult(source.SourceId, observations ?? Array.Empty(), null); + } + catch (Exception error) when (!(error is OperationCanceledException && cancellationToken.IsCancellationRequested)) + { + return new LookupResult(source.SourceId, Array.Empty(), error); + } + } + + private void Emit(CultMeshDiagnosticKind kind, string operationId, string subjectId, string state, string reason, string source) + { + _options.Diagnostics.Emit(new CultMeshDiagnosticEvent( + Interlocked.Increment(ref _diagnosticSequence), _options.Clock.UtcNow, + CultMeshReliabilityOrgan.Discovery, kind, operationId, subjectId, state, + reason, source, subjectId, CultMeshDiscoverySchemaVersions.State)); + } + + public void Dispose() + { + if (_disposed) return; + _disposed = true; + _updates.Dispose(); + } + + private void ThrowIfDisposed() + { + if (_disposed) throw new ObjectDisposedException(nameof(CultMeshDiscoveryService)); + } + + private sealed class LookupResult + { + public LookupResult(string sourceId, IReadOnlyList observations, Exception? error) + { + SourceId = sourceId; + Observations = observations; + Error = error; + } + + public string SourceId { get; } + public IReadOnlyList Observations { get; } + public Exception? Error { get; } + } + } + + [MessagePackObject] + [CultDocument("gamecult.mesh.discovery_state", CultMeshDiscoverySchemaVersions.State)] + public sealed class CultMeshDiscoveryStateDocument + { + [Key(0), CultName] public string EndpointId { get; set; } = ""; + [Key(1)] public CultMeshDiscoveryFreshness Freshness { get; set; } + [Key(2)] public string EvaluatedAtUtc { get; set; } = ""; + [Key(3)] public string? RetryAfterUtc { get; set; } + [Key(4)] public string[] FailedSourceIds { get; set; } = Array.Empty(); + [Key(5)] public CultMeshDiscoveryCandidateDocument[] Candidates { get; set; } = Array.Empty(); + [Key(6)] public string QueryKey { get; set; } = ""; + } + + [MessagePackObject] + public sealed class CultMeshDiscoveryCandidateDocument + { + [Key(0)] public CultMeshVerseDescriptorMessage Descriptor { get; set; } = new CultMeshVerseDescriptorMessage(); + [Key(1)] public string SourceId { get; set; } = ""; + [Key(2)] public string ObservedAtUtc { get; set; } = ""; + [Key(3)] public string ExpiresAtUtc { get; set; } = ""; + [Key(4)] public CultMeshDiscoveryTrust Trust { get; set; } + } + + public sealed class CultMeshCultCacheDiscoveryStore : ICultMeshDiscoveryStore + { + private readonly CultCache _cache; + + public CultMeshCultCacheDiscoveryStore(CultCache cache) + { + _cache = cache ?? throw new ArgumentNullException(nameof(cache)); + } + + public Task LoadAsync(string endpointId, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var document = _cache.Get(Key(endpointId)); + return Task.FromResult(document == null ? null : FromDocument(document)); + } + + public async Task SaveAsync(CultMeshDiscoveryState state, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + await _cache.UpsertAsync(typeof(CultMeshDiscoveryStateDocument), ToDocument(state), Key(state.QueryKey)).ConfigureAwait(false); + await _cache.FlushAsync().ConfigureAwait(false); + } + + private static CultRecordKey Key(string endpointId) => new CultRecordKey("mesh:discovery:" + StableToken(endpointId)); + + private static string StableToken(string value) + { + using var sha = System.Security.Cryptography.SHA256.Create(); + return string.Concat(sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value ?? "")).Select(item => item.ToString("x2"))); + } + + private static CultMeshDiscoveryStateDocument ToDocument(CultMeshDiscoveryState state) => new CultMeshDiscoveryStateDocument + { + EndpointId = state.EndpointId, + Freshness = state.Freshness, + EvaluatedAtUtc = state.EvaluatedAtUtc.ToString("O"), + RetryAfterUtc = state.RetryAfterUtc?.ToString("O"), + FailedSourceIds = state.FailedSourceIds.ToArray(), + QueryKey = state.QueryKey, + Candidates = state.Candidates.Select(candidate => new CultMeshDiscoveryCandidateDocument + { + Descriptor = candidate.Descriptor.ToMessage(), + SourceId = candidate.SourceId, + ObservedAtUtc = candidate.ObservedAtUtc.ToString("O"), + ExpiresAtUtc = candidate.ExpiresAtUtc.ToString("O"), + Trust = candidate.Trust + }).ToArray() + }; + + private static CultMeshDiscoveryState FromDocument(CultMeshDiscoveryStateDocument document) => new CultMeshDiscoveryState( + document.EndpointId, + document.Freshness, + document.Candidates.Select(candidate => new CultMeshDiscoveryCandidate( + candidate.Descriptor.ToVerseDescriptor(), + candidate.SourceId, + DateTimeOffset.Parse(candidate.ObservedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind), + DateTimeOffset.Parse(candidate.ExpiresAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind), + candidate.Trust)), + DateTimeOffset.Parse(document.EvaluatedAtUtc, null, System.Globalization.DateTimeStyles.RoundtripKind), + string.IsNullOrWhiteSpace(document.RetryAfterUtc) ? null : DateTimeOffset.Parse(document.RetryAfterUtc, null, System.Globalization.DateTimeStyles.RoundtripKind), + document.FailedSourceIds, + string.IsNullOrWhiteSpace(document.QueryKey) ? document.EndpointId : document.QueryKey); + } +} diff --git a/src/GameCult.Mesh/CultMeshVerseDiscovery.cs b/src/GameCult.Mesh/CultMeshVerseDiscovery.cs index 0955a99b..69cc9e12 100644 --- a/src/GameCult.Mesh/CultMeshVerseDiscovery.cs +++ b/src/GameCult.Mesh/CultMeshVerseDiscovery.cs @@ -171,6 +171,12 @@ namespace GameCult.Mesh /// Gets or sets the identity of this bootstrap lookup source. public string SourceId { get; set; } = "configured-bootstrap"; + + /// Gets or sets how long a successful compatibility observation remains fresh. + public TimeSpan ObservationTtl { get; set; } = TimeSpan.FromMinutes(5); + + /// Gets or sets the persistent last-known-good discovery store. + public ICultMeshDiscoveryStore? DiscoveryStore { get; set; } } /// @@ -187,6 +193,8 @@ namespace GameCult.Mesh public CultMeshVerseDiscoveryClient(CultMeshVerseDiscoveryClientOptions? options = null) { _options = options ?? new CultMeshVerseDiscoveryClientOptions(); + if (_options.ObservationTtl <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(options), "Discovery observation TTL must be greater than zero."); } /// @@ -258,18 +266,25 @@ namespace GameCult.Mesh if (catalog == null) throw new ArgumentNullException(nameof(catalog)); if (endpoints == null) throw new ArgumentNullException(nameof(endpoints)); - var count = 0; - foreach (var endpoint in endpoints.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal)) - { - var response = await FetchAsync(endpoint, new CultMeshVerseCatalogRequestMessage + var eligible = endpoints.Where(value => !string.IsNullOrWhiteSpace(value)) + .Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray(); + if (eligible.Length == 0) return 0; + var identity = "compatibility:" + (transportVersion ?? "any") + ":" + string.Join("|", eligible); + using var service = new CultMeshDiscoveryService( + eligible.Select(endpoint => new CompatibilityLookupSource(this, endpoint, transportVersion)), + new CultMeshDiscoveryServiceOptions { - TransportVersion = transportVersion - }).ConfigureAwait(false); - catalog.Upsert(response); - count += response.Verses.Length; + Clock = _options.Clock, + Diagnostics = _options.Diagnostics, + Store = _options.DiscoveryStore + }); + var state = await service.ResolveAsync(new CultMeshDiscoveryQuery(identity)).ConfigureAwait(false); + foreach (var candidate in state.Candidates) + { + catalog.Upsert(candidate.Descriptor); } - return count; + return state.Candidates.Count; } private ICultNetSchemaClient CreateClient(string endpoint) @@ -354,5 +369,39 @@ namespace GameCult.Mesh if (error is InvalidOperationException) return "transport_failure"; return "lookup_failure"; } + + private sealed class CompatibilityLookupSource : ICultMeshLookupSource + { + private readonly CultMeshVerseDiscoveryClient _owner; + private readonly string _endpoint; + private readonly string? _transportVersion; + + public CompatibilityLookupSource(CultMeshVerseDiscoveryClient owner, string endpoint, string? transportVersion) + { + _owner = owner; + _endpoint = endpoint; + _transportVersion = transportVersion; + } + + public string SourceId => _endpoint; + + public async Task> LookupAsync( + CultMeshDiscoveryQuery query, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var response = await _owner.FetchAsync( + _endpoint, + new CultMeshVerseCatalogRequestMessage { TransportVersion = _transportVersion }).ConfigureAwait(false); + var observedAt = _owner._options.Clock.UtcNow; + return response.Verses.Select(message => new CultMeshDiscoveryObservation( + message.ToVerseDescriptor(), + SourceId, + observedAt, + observedAt + _owner._options.ObservationTtl, + CultMeshDiscoveryTrust.Unsigned, + response.SchemaVersion)).ToArray(); + } + } } } diff --git a/src/GameCult.Mesh/docs/reliability-migration-plan.md b/src/GameCult.Mesh/docs/reliability-migration-plan.md index 1ec8067d..d3d27077 100644 --- a/src/GameCult.Mesh/docs/reliability-migration-plan.md +++ b/src/GameCult.Mesh/docs/reliability-migration-plan.md @@ -295,6 +295,55 @@ retain an independent endpoint loop or catalog opinion. - A poisoned or unsigned observation cannot override an accepted signed candidate. +### Phase 1 Body Map + +**Owner:** `CultMeshDiscoveryService` owns current candidate observations, +freshness, source failures, positive/negative expiry, and shared in-flight +lookup work for a stable identity plus constraints. + +**Inputs:** `ICultMeshLookupSource` observations, injected clock, optional +`ICultMeshDiscoveryStore`, query identity/Verse constraints, and caller-local +cancellation. + +**Outputs:** watchable `CultMeshDiscoveryState` projections with fresh, +degraded, stale, or unavailable status; persisted +`gamecult.mesh.discovery_state.v1` last-known-good documents; typed diagnostic +events. + +**Derived state:** failed-source lists, retry-after time, candidate ordering, +and legacy `CultMeshVerseCatalog` contents. The catalog is no longer a lookup +writer. + +**Forbidden writers:** lookup sources cannot replace the candidate set, caller +cancellation cannot cancel shared lookup work, and rejected observations cannot +override accepted candidates. + +**Shared paths:** direct service callers and compatibility `DiscoverAsync` +both use concurrent source lookup and the same freshness merge. Compatibility +projects the service result into the old catalog only after resolution. + +**Cut line:** sequential fail-fast endpoint lookup and per-response catalog +mutation have been removed from Verse discovery. Physical endpoint lookup +remains available only as a compatibility source observation. + +**State transition:** restart loads the typed CultCache discovery document. +Expired candidates remain inspectable as stale; unavailable results retain a +bounded negative expiry before sources are queried again. + +**Compatibility inventory:** `AetheriaRuntimeVerseDiscovery` remains the only +known caller of `DiscoverAsync(catalog, endpoints)`. It receives the service +projection now and should migrate to watching `CultMeshDiscoveryState` during +the Phase 2 Aetheria session migration. + +**Rollback:** revert the service, store document, and compatibility delegation +as one unit. Do not run sequential catalog mutation alongside service-owned +resolution. + +**Proof:** Mesh tests cover concurrent good/dead sources, shared in-flight work, +caller-local cancellation, negative expiry, signed precedence, stale-on-error, +public state watches, and CultCache restart reconstruction. Networking tests +prove the compatibility method retains a good concurrent source. + ## Phase 2: Long-Lived Sessions ### Cut first diff --git a/tests/GameCult.Mesh.Tests/CultMeshDiscoveryServiceTests.cs b/tests/GameCult.Mesh.Tests/CultMeshDiscoveryServiceTests.cs new file mode 100644 index 00000000..1b0061d6 --- /dev/null +++ b/tests/GameCult.Mesh.Tests/CultMeshDiscoveryServiceTests.cs @@ -0,0 +1,300 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using GameCult.Caching; +using GameCult.Caching.MessagePack; +using NUnit.Framework; +using R3; + +namespace GameCult.Mesh.Tests; + +public sealed class CultMeshDiscoveryServiceTests +{ + [Test] + public async Task Resolve_QueriesSourcesConcurrentlyAndKeepsSuccessfulResult() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + var bothStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var started = 0; + async Task> Lookup(bool fail) + { + if (Interlocked.Increment(ref started) == 2) bothStarted.TrySetResult(); + await bothStarted.Task; + if (fail) throw new IOException("source offline"); + return new[] { Observation("aetheria", "good", clock, TimeSpan.FromMinutes(1), CultMeshDiscoveryTrust.Signed) }; + } + + using var service = new CultMeshDiscoveryService( + new[] + { + new DelegateSource("dead", _ => Lookup(true)), + new DelegateSource("good", _ => Lookup(false)) + }, + new CultMeshDiscoveryServiceOptions { Clock = clock }); + var observed = new List(); + using var subscription = service.Watch().Subscribe(state => observed.Add(state)); + + var state = await service.ResolveAsync(new CultMeshDiscoveryQuery("odin:aetheria")); + + state.Freshness.Should().Be(CultMeshDiscoveryFreshness.Degraded); + state.Candidates.Should().ContainSingle().Which.Descriptor.VerseId.Should().Be("aetheria"); + state.FailedSourceIds.Should().Equal("dead"); + observed.Should().ContainSingle().Which.Should().BeSameAs(state); + } + + [Test] + public async Task Resolve_SharesInflightLookupAcrossConcurrentCallers() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var source = new DelegateSource("odin", async _ => + { + await release.Task; + return new[] { Observation("aetheria", "odin", clock, TimeSpan.FromMinutes(1), CultMeshDiscoveryTrust.Signed) }; + }); + using var service = new CultMeshDiscoveryService(new[] { source }, new CultMeshDiscoveryServiceOptions { Clock = clock }); + var query = new CultMeshDiscoveryQuery("odin:aetheria"); + + var first = service.ResolveAsync(query); + var second = service.ResolveAsync(query); + await WaitUntilAsync(() => source.LookupCount == 1); + release.TrySetResult(); + var states = await Task.WhenAll(first, second); + + source.LookupCount.Should().Be(1); + states[0].Should().BeSameAs(states[1]); + } + + [Test] + public async Task Resolve_CallerCancellationDoesNotCancelSharedLookup() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var source = new DelegateSource("odin", async _ => + { + await release.Task; + return new[] { Observation("aetheria", "odin", clock, TimeSpan.FromMinutes(1), CultMeshDiscoveryTrust.Signed) }; + }); + using var service = new CultMeshDiscoveryService(new[] { source }, new CultMeshDiscoveryServiceOptions { Clock = clock }); + using var cancelledCaller = new CancellationTokenSource(); + var query = new CultMeshDiscoveryQuery("odin:aetheria"); + + var cancelled = service.ResolveAsync(query, cancelledCaller.Token); + var survivor = service.ResolveAsync(query); + await WaitUntilAsync(() => source.LookupCount == 1); + cancelledCaller.Cancel(); + Assert.ThrowsAsync(async () => await cancelled); + release.TrySetResult(); + + (await survivor).Candidates.Should().ContainSingle(); + source.LookupCount.Should().Be(1); + } + + [Test] + public async Task Resolve_HonorsNegativeExpiryWithoutRepeatingLookup() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + var source = new DelegateSource("odin", _ => + Task.FromException>(new IOException("offline"))); + using var service = new CultMeshDiscoveryService( + new[] { source }, + new CultMeshDiscoveryServiceOptions { Clock = clock, NegativeTtl = TimeSpan.FromSeconds(30) }); + var query = new CultMeshDiscoveryQuery("odin:aetheria"); + + (await service.ResolveAsync(query)).Freshness.Should().Be(CultMeshDiscoveryFreshness.Unavailable); + (await service.ResolveAsync(query)).Freshness.Should().Be(CultMeshDiscoveryFreshness.Unavailable); + source.LookupCount.Should().Be(1); + + clock.Advance(TimeSpan.FromSeconds(31)); + await service.ResolveAsync(query); + source.LookupCount.Should().Be(2); + } + + [Test] + public async Task Resolve_KeepsDifferentlyConstrainedProjectionsIsolated() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + var source = new DelegateSource("odin", _ => Task.FromResult>( + new[] + { + Observation("aetheria", "odin", clock, TimeSpan.FromMinutes(1), CultMeshDiscoveryTrust.Signed), + Observation("norn", "odin", clock, TimeSpan.FromMinutes(1), CultMeshDiscoveryTrust.Signed) + })); + using var service = new CultMeshDiscoveryService(new[] { source }, new CultMeshDiscoveryServiceOptions { Clock = clock }); + + var aetheria = await service.ResolveAsync(new CultMeshDiscoveryQuery("odin:games", new[] { "aetheria" })); + var norn = await service.ResolveAsync(new CultMeshDiscoveryQuery("odin:games", new[] { "norn" })); + + aetheria.Candidates.Select(candidate => candidate.Descriptor.VerseId).Should().Equal("aetheria"); + norn.Candidates.Select(candidate => candidate.Descriptor.VerseId).Should().Equal("norn"); + aetheria.QueryKey.Should().NotBe(norn.QueryKey); + source.LookupCount.Should().Be(2); + } + + [Test] + public async Task Resolve_PreservesExpiredLastKnownGoodAsStaleAfterFailure() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + var failing = false; + var source = new DelegateSource("odin", _ => failing + ? Task.FromException>(new IOException("partition")) + : Task.FromResult>( + new[] { Observation("aetheria", "odin", clock, TimeSpan.FromSeconds(5), CultMeshDiscoveryTrust.Signed) })); + using var service = new CultMeshDiscoveryService(new[] { source }, new CultMeshDiscoveryServiceOptions { Clock = clock }); + var query = new CultMeshDiscoveryQuery("odin:aetheria"); + + (await service.ResolveAsync(query)).Freshness.Should().Be(CultMeshDiscoveryFreshness.Fresh); + clock.Advance(TimeSpan.FromSeconds(6)); + failing = true; + var stale = await service.ResolveAsync(query); + + stale.Freshness.Should().Be(CultMeshDiscoveryFreshness.Stale); + stale.Candidates.Should().ContainSingle().Which.Descriptor.VerseId.Should().Be("aetheria"); + } + + [Test] + public async Task Current_DerivesStaleStateImmediatelyAfterCandidateExpiry() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + using var service = new CultMeshDiscoveryService( + new[] + { + new DelegateSource("odin", _ => Task.FromResult>( + new[] { Observation("aetheria", "odin", clock, TimeSpan.FromSeconds(5), CultMeshDiscoveryTrust.Signed) })) + }, + new CultMeshDiscoveryServiceOptions { Clock = clock }); + await service.ResolveAsync(new CultMeshDiscoveryQuery("odin:aetheria")); + + clock.Advance(TimeSpan.FromSeconds(6)); + + service.Current("odin:aetheria")!.Freshness.Should().Be(CultMeshDiscoveryFreshness.Stale); + } + + [Test] + public async Task Resolve_SignedCandidateCannotBeOverriddenByRejectedObservation() + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + var signed = Observation("aetheria", "odin", clock, TimeSpan.FromMinutes(1), CultMeshDiscoveryTrust.Signed, "rudp://trusted:3076"); + var poisoned = Observation("aetheria", "gossip", clock, TimeSpan.FromMinutes(2), CultMeshDiscoveryTrust.Rejected, "rudp://poison:3076"); + using var service = new CultMeshDiscoveryService( + new[] + { + new DelegateSource("odin", _ => Task.FromResult>(new[] { signed })), + new DelegateSource("gossip", _ => Task.FromResult>(new[] { poisoned })) + }, + new CultMeshDiscoveryServiceOptions { Clock = clock }); + + var state = await service.ResolveAsync(new CultMeshDiscoveryQuery("odin:aetheria")); + + state.Candidates.Should().ContainSingle(); + state.Candidates[0].SourceId.Should().Be("odin"); + state.Candidates[0].Descriptor.DiscoveryEndpoints.Should().Equal("rudp://trusted:3076"); + } + + [Test] + public async Task CultCacheStore_ReconstructsLastKnownGoodAfterRestart() + { + var root = Path.Combine(Path.GetTempPath(), "cultmesh-discovery-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + var path = Path.Combine(root, "discovery.cc"); + try + { + var clock = new ManualClock(new DateTimeOffset(2026, 7, 12, 20, 0, 0, TimeSpan.Zero)); + using (var cache = new CultCache()) + { + cache.AddBackingStore(new SingleFileMessagePackBackingStore(path)); + using var writer = new CultMeshDiscoveryService( + new[] + { + new DelegateSource("odin", _ => Task.FromResult>( + new[] { Observation("aetheria", "odin", clock, TimeSpan.FromMinutes(1), CultMeshDiscoveryTrust.Signed) })) + }, + new CultMeshDiscoveryServiceOptions { Clock = clock, Store = new CultMeshCultCacheDiscoveryStore(cache) }); + (await writer.ResolveAsync(new CultMeshDiscoveryQuery("odin:aetheria"))).Freshness + .Should().Be(CultMeshDiscoveryFreshness.Fresh); + } + + clock.Advance(TimeSpan.FromMinutes(2)); + using var restoredCache = new CultCache(); + restoredCache.AddBackingStore(new SingleFileMessagePackBackingStore(path)); + await restoredCache.PullAllBackingStoresAsync(); + using var reader = new CultMeshDiscoveryService( + new[] { new DelegateSource("odin", _ => Task.FromException>(new IOException("offline"))) }, + new CultMeshDiscoveryServiceOptions { Clock = clock, Store = new CultMeshCultCacheDiscoveryStore(restoredCache) }); + + var restored = await reader.ResolveAsync(new CultMeshDiscoveryQuery("odin:aetheria")); + restored.Freshness.Should().Be(CultMeshDiscoveryFreshness.Stale); + restored.Candidates.Should().ContainSingle().Which.SourceId.Should().Be("odin"); + } + finally + { + if (Directory.Exists(root)) Directory.Delete(root, recursive: true); + } + } + + private static CultMeshDiscoveryObservation Observation( + string verseId, + string sourceId, + ManualClock clock, + TimeSpan ttl, + CultMeshDiscoveryTrust trust, + string endpoint = "rudp://aetheria:3076") => new( + new CultMeshVerseDescriptor( + verseId, + "Aetheria", + CultMeshVerseAuthorityModel.OperatorCluster, + new CultMeshVerseCompatibility("cultmesh.v0", "rules"), + new[] { endpoint }), + sourceId, + clock.UtcNow, + clock.UtcNow + ttl, + trust); + + private static async Task WaitUntilAsync(Func condition) + { + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(2); + while (!condition() && DateTime.UtcNow < deadline) await Task.Delay(1); + condition().Should().BeTrue(); + } + + private sealed class DelegateSource : ICultMeshLookupSource + { + private readonly Func>> _lookup; + + public DelegateSource(string sourceId, Func>> lookup) + { + SourceId = sourceId; + _lookup = lookup; + } + + public string SourceId { get; } + public int LookupCount => Volatile.Read(ref _lookupCount); + + public Task> LookupAsync( + CultMeshDiscoveryQuery query, + CancellationToken cancellationToken = default) + { + Interlocked.Increment(ref _lookupCount); + return _lookup(query); + } + + private int _lookupCount; + } + + private sealed class ManualClock : ICultMeshClock + { + public ManualClock(DateTimeOffset utcNow) => UtcNow = utcNow; + public DateTimeOffset UtcNow { get; private set; } + public Task DelayAsync(TimeSpan delay, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + UtcNow += delay; + return Task.CompletedTask; + } + public void Advance(TimeSpan duration) => UtcNow += duration; + } +} diff --git a/tests/GameCult.Networking.Tests/NetworkingTests.cs b/tests/GameCult.Networking.Tests/NetworkingTests.cs index a08dc846..38b51eec 100644 --- a/tests/GameCult.Networking.Tests/NetworkingTests.cs +++ b/tests/GameCult.Networking.Tests/NetworkingTests.cs @@ -1,5 +1,6 @@ #nullable enable using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; @@ -2821,6 +2822,39 @@ namespace GameCult.Networking.Tests Assert.That(timeline[1].LibraryVersion, Is.Not.Empty); } + [Test] + public async Task CultMeshVerseDiscoveryClient_CompatibilityDiscoveryKeepsGoodConcurrentSource() + { + var clients = new ConcurrentQueue(); + clients.Enqueue(new NeverConnectedSchemaClient()); + clients.Enqueue(new CapturingSchemaClient(message => + { + var request = (CultMeshVerseCatalogRequestMessage)message; + return new CultMeshVerseCatalogResponseMessage + { + MessageId = request.MessageId, + Verses = [new CultMeshVerseDescriptor( + "aetheria", "Aetheria", CultMeshVerseAuthorityModel.OperatorCluster, + new CultMeshVerseCompatibility("cultmesh.v0", "rules"), + discoveryEndpoints: ["rudp://aetheria:3076"]).ToMessage()] + }; + })); + var client = new CultMeshVerseDiscoveryClient(new CultMeshVerseDiscoveryClientOptions + { + CreateClient = () => clients.TryDequeue(out var next) ? next : throw new InvalidOperationException("Unexpected client."), + Clock = new ManualCultMeshClock(new DateTimeOffset(2026, 7, 12, 18, 0, 0, TimeSpan.Zero)), + ConnectTimeout = TimeSpan.FromMilliseconds(50) + }); + using var catalog = new CultMeshVerseCatalog(); + + var count = await client.DiscoverAsync( + catalog, + new[] { "rudp://dead.example.test:4075", "rudp://good.example.test:4075" }); + + Assert.That(count, Is.EqualTo(1)); + Assert.That(catalog.Verses.Single().VerseId, Is.EqualTo("aetheria")); + } + [Test] public async Task CultMeshPeerExchangeClient_Uses_SchemaClientPort() {