Move Verse discovery ownership into CultMesh
This commit is contained in:
parent
fc65e25fd5
commit
0a678c6e3a
5 changed files with 902 additions and 9 deletions
461
src/GameCult.Mesh/CultMeshDiscoveryService.cs
Normal file
461
src/GameCult.Mesh/CultMeshDiscoveryService.cs
Normal file
|
|
@ -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<string>? 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<string>();
|
||||
}
|
||||
|
||||
public string EndpointId { get; }
|
||||
public IReadOnlyList<string> 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<IReadOnlyList<CultMeshDiscoveryObservation>> LookupAsync(
|
||||
CultMeshDiscoveryQuery query,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public interface ICultMeshDiscoveryStore
|
||||
{
|
||||
Task<CultMeshDiscoveryState?> 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<CultMeshDiscoveryCandidate>? candidates,
|
||||
DateTimeOffset evaluatedAtUtc,
|
||||
DateTimeOffset? retryAfterUtc = null,
|
||||
IEnumerable<string>? failedSourceIds = null,
|
||||
string? queryKey = null)
|
||||
{
|
||||
EndpointId = endpointId ?? "";
|
||||
Freshness = freshness;
|
||||
Candidates = candidates?.OrderBy(candidate => candidate.Descriptor.VerseId, StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<CultMeshDiscoveryCandidate>();
|
||||
EvaluatedAtUtc = evaluatedAtUtc;
|
||||
RetryAfterUtc = retryAfterUtc;
|
||||
FailedSourceIds = failedSourceIds?.Distinct(StringComparer.Ordinal).OrderBy(value => value, StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<string>();
|
||||
QueryKey = string.IsNullOrWhiteSpace(queryKey) ? EndpointId : queryKey;
|
||||
}
|
||||
|
||||
public string EndpointId { get; }
|
||||
public CultMeshDiscoveryFreshness Freshness { get; }
|
||||
public IReadOnlyList<CultMeshDiscoveryCandidate> Candidates { get; }
|
||||
public DateTimeOffset EvaluatedAtUtc { get; }
|
||||
public DateTimeOffset? RetryAfterUtc { get; }
|
||||
public IReadOnlyList<string> 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<string, Lazy<Task<CultMeshDiscoveryState>>> _inFlight = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, CultMeshDiscoveryState> _states = new(StringComparer.Ordinal);
|
||||
private readonly Subject<CultMeshDiscoveryState> _updates = new();
|
||||
private long _diagnosticSequence;
|
||||
private bool _disposed;
|
||||
|
||||
public CultMeshDiscoveryService(
|
||||
IEnumerable<ICultMeshLookupSource> 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<CultMeshDiscoveryState> 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<CultMeshDiscoveryState> 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<Task<CultMeshDiscoveryState>>(
|
||||
() => 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<T> AwaitForCallerAsync<T>(Task<T> shared, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!cancellationToken.CanBeCanceled)
|
||||
return await shared.ConfigureAwait(false);
|
||||
var cancelled = new TaskCompletionSource<bool>(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<CultMeshDiscoveryState> 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<CultMeshDiscoveryCandidate> candidates = accepted.Length > 0
|
||||
? accepted
|
||||
: previous?.Candidates ?? Array.Empty<CultMeshDiscoveryCandidate>();
|
||||
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<CultMeshDiscoveryState?> 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<LookupResult> 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<CultMeshDiscoveryObservation>(), null);
|
||||
}
|
||||
catch (Exception error) when (!(error is OperationCanceledException && cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
return new LookupResult(source.SourceId, Array.Empty<CultMeshDiscoveryObservation>(), 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<CultMeshDiscoveryObservation> observations, Exception? error)
|
||||
{
|
||||
SourceId = sourceId;
|
||||
Observations = observations;
|
||||
Error = error;
|
||||
}
|
||||
|
||||
public string SourceId { get; }
|
||||
public IReadOnlyList<CultMeshDiscoveryObservation> 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<string>();
|
||||
[Key(5)] public CultMeshDiscoveryCandidateDocument[] Candidates { get; set; } = Array.Empty<CultMeshDiscoveryCandidateDocument>();
|
||||
[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<CultMeshDiscoveryState?> LoadAsync(string endpointId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var document = _cache.Get<CultMeshDiscoveryStateDocument>(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);
|
||||
}
|
||||
}
|
||||
|
|
@ -171,6 +171,12 @@ namespace GameCult.Mesh
|
|||
|
||||
/// <summary>Gets or sets the identity of this bootstrap lookup source.</summary>
|
||||
public string SourceId { get; set; } = "configured-bootstrap";
|
||||
|
||||
/// <summary>Gets or sets how long a successful compatibility observation remains fresh.</summary>
|
||||
public TimeSpan ObservationTtl { get; set; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>Gets or sets the persistent last-known-good discovery store.</summary>
|
||||
public ICultMeshDiscoveryStore? DiscoveryStore { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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<IReadOnlyList<CultMeshDiscoveryObservation>> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
300
tests/GameCult.Mesh.Tests/CultMeshDiscoveryServiceTests.cs
Normal file
300
tests/GameCult.Mesh.Tests/CultMeshDiscoveryServiceTests.cs
Normal file
|
|
@ -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<IReadOnlyList<CultMeshDiscoveryObservation>> 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<CultMeshDiscoveryState>();
|
||||
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<OperationCanceledException>(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<IReadOnlyList<CultMeshDiscoveryObservation>>(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<IReadOnlyList<CultMeshDiscoveryObservation>>(
|
||||
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<IReadOnlyList<CultMeshDiscoveryObservation>>(new IOException("partition"))
|
||||
: Task.FromResult<IReadOnlyList<CultMeshDiscoveryObservation>>(
|
||||
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<IReadOnlyList<CultMeshDiscoveryObservation>>(
|
||||
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<IReadOnlyList<CultMeshDiscoveryObservation>>(new[] { signed })),
|
||||
new DelegateSource("gossip", _ => Task.FromResult<IReadOnlyList<CultMeshDiscoveryObservation>>(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<IReadOnlyList<CultMeshDiscoveryObservation>>(
|
||||
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<IReadOnlyList<CultMeshDiscoveryObservation>>(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<bool> 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<CultMeshDiscoveryQuery, Task<IReadOnlyList<CultMeshDiscoveryObservation>>> _lookup;
|
||||
|
||||
public DelegateSource(string sourceId, Func<CultMeshDiscoveryQuery, Task<IReadOnlyList<CultMeshDiscoveryObservation>>> lookup)
|
||||
{
|
||||
SourceId = sourceId;
|
||||
_lookup = lookup;
|
||||
}
|
||||
|
||||
public string SourceId { get; }
|
||||
public int LookupCount => Volatile.Read(ref _lookupCount);
|
||||
|
||||
public Task<IReadOnlyList<CultMeshDiscoveryObservation>> 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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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<ICultNetSchemaClient>();
|
||||
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()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue