Recover authority-bound CultMesh and atomic generations
This commit is contained in:
commit
334e60f192
92 changed files with 6071 additions and 688 deletions
|
|
@ -2,6 +2,7 @@ using System;
|
|||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using R3;
|
||||
|
|
@ -297,6 +298,11 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the durable store for accepted shard mutation logs.
|
||||
/// </summary>
|
||||
public ICultNetShardMutationLogStore? MutationLogStore { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether authoritative writes must occur inside ExecuteTransactionAsync.
|
||||
/// Use this for state owners that forbid record-at-a-time mutation bypasses.
|
||||
/// </summary>
|
||||
public bool RequireTransactionsForAuthoritativeWrites { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -464,6 +470,8 @@ namespace GameCult.Networking
|
|||
private readonly Dictionary<string, long> _nextLogSequences = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, long> _appliedShardSequences = new(StringComparer.Ordinal);
|
||||
private readonly Subject<object> _changes = new();
|
||||
private readonly AsyncLocal<CultNetDatabaseTransaction?> _ambientTransaction = new();
|
||||
private readonly bool _requireTransactionsForAuthoritativeWrites;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -476,6 +484,7 @@ namespace GameCult.Networking
|
|||
_runtimeId = options.RuntimeId;
|
||||
_documents = options.DocumentRegistry ?? new CultNetDocumentRegistry(cache.Registry);
|
||||
_mutationLogStore = options.MutationLogStore;
|
||||
_requireTransactionsForAuthoritativeWrites = options.RequireTransactionsForAuthoritativeWrites;
|
||||
_shards = (options.Shards == null || options.Shards.Count == 0
|
||||
? new[] { CultNetShardDescriptor.PrimaryAll(options.RuntimeId) }
|
||||
: options.Shards)
|
||||
|
|
@ -503,6 +512,49 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public IReadOnlyList<CultNetClientAuthorityScope> ClientAuthorityScopes => _clientAuthorityScopes;
|
||||
|
||||
/// <summary>
|
||||
/// Runs one buffered authoritative database mutation. Cache state, durable state,
|
||||
/// mutation logs, and database observers advance only after the complete stage succeeds.
|
||||
/// </summary>
|
||||
public async Task ExecuteTransactionAsync(Func<Task> stageAsync, bool soft = false)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (stageAsync == null) throw new ArgumentNullException(nameof(stageAsync));
|
||||
if (_ambientTransaction.Value != null)
|
||||
{
|
||||
await stageAsync().ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
var transaction = new CultNetDatabaseTransaction();
|
||||
IReadOnlyList<Action> afterCommit;
|
||||
_ambientTransaction.Value = transaction;
|
||||
try
|
||||
{
|
||||
await _cache.ExecuteTransactionAsync(stageAsync, soft).ConfigureAwait(false);
|
||||
afterCommit = transaction.AfterCommit.ToArray();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_ambientTransaction.Value = null;
|
||||
}
|
||||
|
||||
foreach (var publish in afterCommit)
|
||||
publish();
|
||||
}
|
||||
|
||||
/// <summary>Runs one value-producing buffered authoritative database mutation.</summary>
|
||||
public async Task<T> ExecuteTransactionAsync<T>(Func<Task<T>> stageAsync, bool soft = false)
|
||||
{
|
||||
if (stageAsync == null) throw new ArgumentNullException(nameof(stageAsync));
|
||||
T result = default!;
|
||||
await ExecuteTransactionAsync(async () =>
|
||||
{
|
||||
result = await stageAsync().ConfigureAwait(false);
|
||||
}, soft).ConfigureAwait(false);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Gets whether this database instance can authoritatively replace the document at a key.</summary>
|
||||
public bool CanWriteAuthoritatively<T>(CultRecordKey key) where T : class
|
||||
{
|
||||
|
|
@ -817,6 +869,7 @@ namespace GameCult.Networking
|
|||
public async Task<CultRecordHandle<T>> PutAsync<T>(CultRecordKey key, T document) where T : class
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
EnsureAuthoritativeTransaction();
|
||||
if (document == null) throw new ArgumentNullException(nameof(document));
|
||||
|
||||
var descriptor = _cache.Registry.GetRequired<T>();
|
||||
|
|
@ -825,20 +878,27 @@ namespace GameCult.Networking
|
|||
|
||||
var previous = _cache.Get<T>(key);
|
||||
var handle = await _cache.UpsertAsync(document, new CultRecordHandle<T>(key)).ConfigureAwait(false);
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document,
|
||||
previous);
|
||||
Publish(new CultNetDatabaseChange<T>(
|
||||
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document,
|
||||
previous));
|
||||
void PublishCommittedPut()
|
||||
{
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document,
|
||||
previous);
|
||||
Publish(new CultNetDatabaseChange<T>(
|
||||
previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document,
|
||||
previous));
|
||||
}
|
||||
if (_ambientTransaction.Value is { } transaction)
|
||||
transaction.AfterCommit.Add(PublishCommittedPut);
|
||||
else
|
||||
PublishCommittedPut();
|
||||
return handle;
|
||||
}
|
||||
|
||||
|
|
@ -873,6 +933,7 @@ namespace GameCult.Networking
|
|||
public Task DeleteAsync<T>(CultRecordKey key) where T : class
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
EnsureAuthoritativeTransaction();
|
||||
var descriptor = _cache.Registry.GetRequired<T>();
|
||||
var shard = ResolveShardInternal(descriptor, key);
|
||||
EnsurePrimary(shard, descriptor.SchemaId, key);
|
||||
|
|
@ -881,20 +942,27 @@ namespace GameCult.Networking
|
|||
if (previous != null)
|
||||
{
|
||||
_cache.Remove(new CultRecordHandle<T>(key));
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document: null,
|
||||
previousDocument: previous);
|
||||
Publish(new CultNetDatabaseChange<T>(
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document: null,
|
||||
previousDocument: previous));
|
||||
void PublishCommittedDelete()
|
||||
{
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document: null,
|
||||
previousDocument: previous);
|
||||
Publish(new CultNetDatabaseChange<T>(
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document: null,
|
||||
previousDocument: previous));
|
||||
}
|
||||
if (_ambientTransaction.Value is { } transaction)
|
||||
transaction.AfterCommit.Add(PublishCommittedDelete);
|
||||
else
|
||||
PublishCommittedDelete();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
|
|
@ -906,6 +974,7 @@ namespace GameCult.Networking
|
|||
public async Task<object> ApplyPutAsync(CultNetDocumentPutRawMessage message)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
EnsureAuthoritativeTransaction();
|
||||
if (message == null) throw new ArgumentNullException(nameof(message));
|
||||
if (message.Document == null)
|
||||
{
|
||||
|
|
@ -920,31 +989,41 @@ namespace GameCult.Networking
|
|||
var document = await _documents.ApplyRawDocumentPutMessageAsync(_cache, message).ConfigureAwait(false);
|
||||
var kind = previous == null ? CultNetDatabaseChangeKind.Added : CultNetDatabaseChangeKind.Updated;
|
||||
var predictionKey = PredictionKey(descriptor.SchemaId, key);
|
||||
if (_predictedDocuments.Remove(predictionKey))
|
||||
var reconcilesPrediction = _predictedDocuments.ContainsKey(predictionKey);
|
||||
if (reconcilesPrediction)
|
||||
{
|
||||
kind = CultNetDatabaseChangeKind.Reconciled;
|
||||
}
|
||||
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
kind == CultNetDatabaseChangeKind.Reconciled ? CultNetDatabaseChangeKind.Updated : kind,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document,
|
||||
previous,
|
||||
new CultNetShardLogEntryMessage
|
||||
{
|
||||
ChangeKind = previous == null ? "added" : "updated",
|
||||
Put = message
|
||||
});
|
||||
PublishUntyped(
|
||||
descriptor.DocumentType,
|
||||
kind,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document,
|
||||
previous);
|
||||
void PublishCommittedPut()
|
||||
{
|
||||
if (reconcilesPrediction)
|
||||
_predictedDocuments.Remove(predictionKey);
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
kind == CultNetDatabaseChangeKind.Reconciled ? CultNetDatabaseChangeKind.Updated : kind,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document,
|
||||
previous,
|
||||
new CultNetShardLogEntryMessage
|
||||
{
|
||||
ChangeKind = previous == null ? "added" : "updated",
|
||||
Put = message
|
||||
});
|
||||
PublishUntyped(
|
||||
descriptor.DocumentType,
|
||||
kind,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document,
|
||||
previous);
|
||||
}
|
||||
if (_ambientTransaction.Value is { } transaction)
|
||||
transaction.AfterCommit.Add(PublishCommittedPut);
|
||||
else
|
||||
PublishCommittedPut();
|
||||
return document;
|
||||
}
|
||||
|
||||
|
|
@ -954,6 +1033,7 @@ namespace GameCult.Networking
|
|||
public Task ApplyDeleteAsync(CultNetDocumentDeleteMessage message)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
EnsureAuthoritativeTransaction();
|
||||
if (message == null) throw new ArgumentNullException(nameof(message));
|
||||
|
||||
var key = new CultRecordKey(message.RecordKey);
|
||||
|
|
@ -967,26 +1047,33 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
_cache.Remove(key);
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document: null,
|
||||
previousDocument: previous,
|
||||
wireEntry: new CultNetShardLogEntryMessage
|
||||
{
|
||||
ChangeKind = "removed",
|
||||
Delete = message
|
||||
});
|
||||
PublishUntyped(
|
||||
descriptor.DocumentType,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document: null,
|
||||
previousDocument: previous);
|
||||
void PublishCommittedDelete()
|
||||
{
|
||||
AppendMutationLogEntry(
|
||||
shard,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
document: null,
|
||||
previousDocument: previous,
|
||||
wireEntry: new CultNetShardLogEntryMessage
|
||||
{
|
||||
ChangeKind = "removed",
|
||||
Delete = message
|
||||
});
|
||||
PublishUntyped(
|
||||
descriptor.DocumentType,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document: null,
|
||||
previousDocument: previous);
|
||||
}
|
||||
if (_ambientTransaction.Value is { } transaction)
|
||||
transaction.AfterCommit.Add(PublishCommittedDelete);
|
||||
else
|
||||
PublishCommittedDelete();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
|
@ -1699,6 +1786,20 @@ namespace GameCult.Networking
|
|||
};
|
||||
}
|
||||
|
||||
private sealed class CultNetDatabaseTransaction
|
||||
{
|
||||
public List<Action> AfterCommit { get; } = new();
|
||||
}
|
||||
|
||||
private void EnsureAuthoritativeTransaction()
|
||||
{
|
||||
if (_requireTransactionsForAuthoritativeWrites && _ambientTransaction.Value == null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"This CultNet database requires authoritative writes to use ExecuteTransactionAsync.");
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed)
|
||||
|
|
|
|||
|
|
@ -13,6 +13,8 @@ namespace GameCult.Networking
|
|||
{
|
||||
/// <summary>
|
||||
/// Publishes live database changes through any schema-v0 server transport.
|
||||
/// Optional record projection runs after authorization and owns both initial
|
||||
/// snapshot and live-update delivery for a peer.
|
||||
/// </summary>
|
||||
public sealed class CultNetDatabaseSubscriptionServer : IDisposable
|
||||
{
|
||||
|
|
@ -20,18 +22,32 @@ namespace GameCult.Networking
|
|||
private readonly CultNetDatabase _database;
|
||||
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, Task> _subscribe;
|
||||
private readonly Func<CultNetDatabaseUnsubscribeMessage, ICultNetSchemaServerPeer, Task> _unsubscribe;
|
||||
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? _authorizeRequest;
|
||||
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? _authorizeRecord;
|
||||
private readonly Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, CultNetRawDocumentRecord, CultNetRawDocumentRecord?>? _projectRecord;
|
||||
private readonly ICultNetSchemaServerPeerLifecycle? _peerLifecycle;
|
||||
private readonly ConcurrentDictionary<SubscriptionKey, IDisposable> _subscriptions =
|
||||
new ConcurrentDictionary<SubscriptionKey, IDisposable>(SubscriptionKeyComparer.Instance);
|
||||
private readonly ConcurrentDictionary<SubscriptionKey, CultNetDatabaseSubscribeMessage> _requests =
|
||||
new ConcurrentDictionary<SubscriptionKey, CultNetDatabaseSubscribeMessage>(SubscriptionKeyComparer.Instance);
|
||||
private readonly ConcurrentDictionary<SubscriptionKey, SubscriptionProjectionState> _projections =
|
||||
new ConcurrentDictionary<SubscriptionKey, SubscriptionProjectionState>(SubscriptionKeyComparer.Instance);
|
||||
private readonly object _lifecycleGate = new();
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>Attaches live database subscription handlers to a schema server.</summary>
|
||||
public CultNetDatabaseSubscriptionServer(ICultNetSchemaServer server, CultNetDatabase database)
|
||||
public CultNetDatabaseSubscriptionServer(
|
||||
ICultNetSchemaServer server,
|
||||
CultNetDatabase database,
|
||||
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, bool>? authorizeRequest = null,
|
||||
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, string, string, bool>? authorizeRecord = null,
|
||||
Func<CultNetDatabaseSubscribeMessage, ICultNetSchemaServerPeer, CultNetRawDocumentRecord, CultNetRawDocumentRecord?>? projectRecord = null)
|
||||
{
|
||||
_server = server ?? throw new ArgumentNullException(nameof(server));
|
||||
_database = database ?? throw new ArgumentNullException(nameof(database));
|
||||
_authorizeRequest = authorizeRequest;
|
||||
_authorizeRecord = authorizeRecord;
|
||||
_projectRecord = projectRecord;
|
||||
_subscribe = HandleSubscribeAsync;
|
||||
_unsubscribe = HandleUnsubscribeAsync;
|
||||
_server.OnCultNet(_subscribe);
|
||||
|
|
@ -48,34 +64,48 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public event Action<CultNetDatabaseSubscriptionDemand>? DemandChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Re-evaluates every live peer projection against current authorization and source state.
|
||||
/// Records that lost visibility are explicitly removed and body demand is withdrawn while
|
||||
/// the request is unauthorized. The subscription intent remains available for a later
|
||||
/// authorized generation on the same established peer.
|
||||
/// </summary>
|
||||
public void Reconcile()
|
||||
{
|
||||
lock (_lifecycleGate)
|
||||
{
|
||||
if (_disposed) return;
|
||||
foreach (var entry in _requests.ToArray())
|
||||
Reconcile(entry.Key, entry.Value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Detaches handlers and releases all active watches.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeMessage>(_subscribe);
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribe);
|
||||
if (_peerLifecycle != null)
|
||||
_peerLifecycle.PeerDisconnected -= HandlePeerDisconnected;
|
||||
foreach (var entry in _subscriptions)
|
||||
lock (_lifecycleGate)
|
||||
{
|
||||
entry.Value.Dispose();
|
||||
if (_requests.TryRemove(entry.Key, out var request))
|
||||
PublishDemand(request, entry.Key, active: false);
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeMessage>(_subscribe);
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribe);
|
||||
if (_peerLifecycle != null)
|
||||
_peerLifecycle.PeerDisconnected -= HandlePeerDisconnected;
|
||||
foreach (var entry in _subscriptions.ToArray())
|
||||
Withdraw(entry.Key, sendRemovals: false, forgetRequest: true);
|
||||
_subscriptions.Clear();
|
||||
_requests.Clear();
|
||||
_projections.Clear();
|
||||
}
|
||||
_subscriptions.Clear();
|
||||
_requests.Clear();
|
||||
}
|
||||
|
||||
private void HandlePeerDisconnected(ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
foreach (var key in _subscriptions.Keys.Where(candidate =>
|
||||
SubscriptionKeyComparer.SamePeer(candidate.Peer, peer)).ToArray())
|
||||
lock (_lifecycleGate)
|
||||
{
|
||||
if (_subscriptions.TryRemove(key, out var subscription))
|
||||
subscription.Dispose();
|
||||
if (_requests.TryRemove(key, out var request))
|
||||
PublishDemand(request, key, active: false);
|
||||
foreach (var key in _subscriptions.Keys.Where(candidate =>
|
||||
SubscriptionKeyComparer.SamePeer(candidate.Peer, peer)).ToArray())
|
||||
Withdraw(key, sendRemovals: false, forgetRequest: true);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -89,39 +119,49 @@ namespace GameCult.Networking
|
|||
peer.SendCultNet(new CultNetErrorMessage { Error = "Database subscription requires a subscriptionId or messageId." });
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var key = new SubscriptionKey(peer, subscriptionId);
|
||||
if (_requests.TryGetValue(key, out var previous))
|
||||
PublishDemand(previous, key, active: false);
|
||||
_subscriptions.AddOrUpdate(
|
||||
key,
|
||||
_ => Watch(request, subscriptionId, peer),
|
||||
(_, current) =>
|
||||
{
|
||||
current.Dispose();
|
||||
return Watch(request, subscriptionId, peer);
|
||||
});
|
||||
_requests[key] = request;
|
||||
PublishDemand(request, key, active: true);
|
||||
if (request.IncludeSnapshot)
|
||||
if (_authorizeRequest?.Invoke(request, peer) == false)
|
||||
{
|
||||
peer.SendCultNet(_database.Documents.CreateRawSnapshotResponse(
|
||||
_database.Cache,
|
||||
request.MessageId,
|
||||
new CultNetSnapshotRequestMessage
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
SchemaIds = request.SchemaIds,
|
||||
RecordKeys = request.RecordKeys
|
||||
}));
|
||||
peer.SendCultNet(new CultNetErrorMessage { Error = "Database subscription is not authorized for this peer." });
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
else
|
||||
|
||||
lock (_lifecycleGate)
|
||||
{
|
||||
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
|
||||
var key = new SubscriptionKey(peer, subscriptionId);
|
||||
Withdraw(key, sendRemovals: true, forgetRequest: true);
|
||||
var projection = new SubscriptionProjectionState();
|
||||
_projections[key] = projection;
|
||||
_requests[key] = request;
|
||||
try
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
Documents = Array.Empty<CultNetRawDocumentRecord>()
|
||||
});
|
||||
_subscriptions[key] = Watch(request, subscriptionId, peer, key);
|
||||
if (request.IncludeSnapshot)
|
||||
{
|
||||
var snapshot = CreateProjectedSnapshot(request, peer);
|
||||
foreach (var entry in snapshot.BySourceRecordKey)
|
||||
projection.DeliveredBySourceRecordKey[entry.Key] = entry.Value;
|
||||
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
Documents = snapshot.Documents
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
peer.SendCultNet(new CultNetSnapshotResponseRawMessage
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
Documents = Array.Empty<CultNetRawDocumentRecord>()
|
||||
});
|
||||
}
|
||||
PublishDemand(request, key, active: true);
|
||||
projection.DemandActive = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Withdraw(key, sendRemovals: false, forgetRequest: true);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
|
@ -134,9 +174,8 @@ namespace GameCult.Networking
|
|||
if (!string.IsNullOrWhiteSpace(subscriptionId))
|
||||
{
|
||||
var key = new SubscriptionKey(peer, subscriptionId);
|
||||
if (_subscriptions.TryRemove(key, out var subscription)) subscription.Dispose();
|
||||
if (_requests.TryRemove(key, out var subscribed))
|
||||
PublishDemand(subscribed, key, active: false);
|
||||
lock (_lifecycleGate)
|
||||
Withdraw(key, sendRemovals: false, forgetRequest: true);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
|
@ -179,19 +218,232 @@ namespace GameCult.Networking
|
|||
private IDisposable Watch(
|
||||
CultNetDatabaseSubscribeMessage request,
|
||||
string subscriptionId,
|
||||
ICultNetSchemaServerPeer peer)
|
||||
ICultNetSchemaServerPeer peer,
|
||||
SubscriptionKey key)
|
||||
{
|
||||
return _database.WatchAllChanges().Subscribe(change =>
|
||||
{
|
||||
var message = CreateChange(change, request, subscriptionId);
|
||||
if (message != null) peer.SendCultNet(message);
|
||||
lock (_lifecycleGate)
|
||||
{
|
||||
if (_disposed || !_requests.ContainsKey(key) || !_projections.TryGetValue(key, out var projection))
|
||||
return;
|
||||
if (_authorizeRequest?.Invoke(request, peer) == false)
|
||||
{
|
||||
Reconcile(key, request);
|
||||
return;
|
||||
}
|
||||
|
||||
var sourceRecordKey = ResolveChangeRecordKey(change);
|
||||
var message = CreateAuthorizedChange(change, request, subscriptionId, peer);
|
||||
var projected = message?.Document;
|
||||
if (projected != null && _projectRecord != null)
|
||||
projected = _projectRecord(request, peer, projected);
|
||||
ApplyProjectedChange(
|
||||
projection,
|
||||
sourceRecordKey,
|
||||
projected,
|
||||
peer,
|
||||
subscriptionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void Reconcile(SubscriptionKey key, CultNetDatabaseSubscribeMessage request)
|
||||
{
|
||||
if (!_projections.TryGetValue(key, out var projection)) return;
|
||||
var authorized = _authorizeRequest?.Invoke(request, key.Peer) != false;
|
||||
var next = authorized
|
||||
? CreateProjectedSnapshot(request, key.Peer)
|
||||
: ProjectedSnapshot.Empty;
|
||||
|
||||
foreach (var previous in projection.DeliveredBySourceRecordKey.ToArray())
|
||||
{
|
||||
if (!next.BySourceRecordKey.TryGetValue(previous.Key, out var current))
|
||||
{
|
||||
SendRemoval(key.Peer, key.Id, previous.Value);
|
||||
continue;
|
||||
}
|
||||
if (!string.Equals(previous.Value.RecordKey, current.RecordKey, StringComparison.Ordinal) ||
|
||||
!string.Equals(previous.Value.SchemaId, current.SchemaId, StringComparison.Ordinal))
|
||||
{
|
||||
SendRemoval(key.Peer, key.Id, previous.Value);
|
||||
SendUpsert(key.Peer, key.Id, current, added: true);
|
||||
}
|
||||
else if (!Equivalent(previous.Value, current))
|
||||
{
|
||||
SendUpsert(key.Peer, key.Id, current, added: false);
|
||||
}
|
||||
}
|
||||
foreach (var current in next.BySourceRecordKey)
|
||||
{
|
||||
if (!projection.DeliveredBySourceRecordKey.ContainsKey(current.Key))
|
||||
SendUpsert(key.Peer, key.Id, current.Value, added: true);
|
||||
}
|
||||
|
||||
projection.DeliveredBySourceRecordKey.Clear();
|
||||
foreach (var current in next.BySourceRecordKey)
|
||||
projection.DeliveredBySourceRecordKey[current.Key] = current.Value;
|
||||
|
||||
if (projection.DemandActive != authorized)
|
||||
{
|
||||
projection.DemandActive = authorized;
|
||||
PublishDemand(request, key, authorized);
|
||||
}
|
||||
}
|
||||
|
||||
private ProjectedSnapshot CreateProjectedSnapshot(
|
||||
CultNetDatabaseSubscribeMessage request,
|
||||
ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
var snapshot = _database.Documents.CreateRawSnapshotResponse(
|
||||
_database.Cache,
|
||||
request.MessageId,
|
||||
new CultNetSnapshotRequestMessage
|
||||
{
|
||||
MessageId = request.MessageId,
|
||||
SchemaIds = request.SchemaIds,
|
||||
RecordKeys = request.RecordKeys
|
||||
});
|
||||
var bySourceRecordKey = new Dictionary<string, CultNetRawDocumentRecord>(StringComparer.Ordinal);
|
||||
var projectedRecordKeys = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var source in snapshot.Documents)
|
||||
{
|
||||
var sourceRecordKey = source.RecordKey;
|
||||
if (_authorizeRecord?.Invoke(request, peer, sourceRecordKey, source.SchemaId) == false)
|
||||
continue;
|
||||
var projected = _projectRecord == null ? source : _projectRecord(request, peer, source);
|
||||
if (projected == null) continue;
|
||||
if (!projectedRecordKeys.Add(projected.RecordKey))
|
||||
throw new InvalidOperationException(
|
||||
$"Database subscription projection produced duplicate record key '{projected.RecordKey}'.");
|
||||
bySourceRecordKey[sourceRecordKey] = projected;
|
||||
}
|
||||
return new ProjectedSnapshot(bySourceRecordKey);
|
||||
}
|
||||
|
||||
private void ApplyProjectedChange(
|
||||
SubscriptionProjectionState projection,
|
||||
string sourceRecordKey,
|
||||
CultNetRawDocumentRecord? current,
|
||||
ICultNetSchemaServerPeer peer,
|
||||
string subscriptionId)
|
||||
{
|
||||
projection.DeliveredBySourceRecordKey.TryGetValue(sourceRecordKey, out var previous);
|
||||
if (current == null)
|
||||
{
|
||||
if (previous != null)
|
||||
{
|
||||
projection.DeliveredBySourceRecordKey.Remove(sourceRecordKey);
|
||||
SendRemoval(peer, subscriptionId, previous);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (previous == null)
|
||||
{
|
||||
projection.DeliveredBySourceRecordKey[sourceRecordKey] = current;
|
||||
SendUpsert(peer, subscriptionId, current, added: true);
|
||||
return;
|
||||
}
|
||||
if (!string.Equals(previous.RecordKey, current.RecordKey, StringComparison.Ordinal) ||
|
||||
!string.Equals(previous.SchemaId, current.SchemaId, StringComparison.Ordinal))
|
||||
{
|
||||
SendRemoval(peer, subscriptionId, previous);
|
||||
projection.DeliveredBySourceRecordKey[sourceRecordKey] = current;
|
||||
SendUpsert(peer, subscriptionId, current, added: true);
|
||||
return;
|
||||
}
|
||||
if (!Equivalent(previous, current))
|
||||
{
|
||||
projection.DeliveredBySourceRecordKey[sourceRecordKey] = current;
|
||||
SendUpsert(peer, subscriptionId, current, added: false);
|
||||
}
|
||||
}
|
||||
|
||||
private static string ResolveChangeRecordKey(object change)
|
||||
{
|
||||
var value = change.GetType().GetProperty("Key")?.GetValue(change);
|
||||
return value is CultRecordKey key ? key.Value : string.Empty;
|
||||
}
|
||||
|
||||
private static bool Equivalent(CultNetRawDocumentRecord left, CultNetRawDocumentRecord right) =>
|
||||
string.Equals(left.SchemaId, right.SchemaId, StringComparison.Ordinal) &&
|
||||
string.Equals(left.SchemaName, right.SchemaName, StringComparison.Ordinal) &&
|
||||
string.Equals(left.SchemaVersion, right.SchemaVersion, StringComparison.Ordinal) &&
|
||||
string.Equals(left.SchemaContentHash, right.SchemaContentHash, StringComparison.Ordinal) &&
|
||||
string.Equals(left.RecordKey, right.RecordKey, StringComparison.Ordinal) &&
|
||||
string.Equals(left.PayloadEncoding, right.PayloadEncoding, StringComparison.Ordinal) &&
|
||||
left.Payload.SequenceEqual(right.Payload) &&
|
||||
string.Equals(left.SourceRuntimeId, right.SourceRuntimeId, StringComparison.Ordinal) &&
|
||||
string.Equals(left.SourceAgentId, right.SourceAgentId, StringComparison.Ordinal) &&
|
||||
string.Equals(left.SourceRole, right.SourceRole, StringComparison.Ordinal);
|
||||
|
||||
private static void SendUpsert(
|
||||
ICultNetSchemaServerPeer peer,
|
||||
string subscriptionId,
|
||||
CultNetRawDocumentRecord document,
|
||||
bool added) =>
|
||||
peer.SendCultNet(new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
SubscriptionId = subscriptionId,
|
||||
ChangeKind = added ? "added" : "updated",
|
||||
Document = document
|
||||
});
|
||||
|
||||
private static void SendRemoval(
|
||||
ICultNetSchemaServerPeer peer,
|
||||
string subscriptionId,
|
||||
CultNetRawDocumentRecord document) =>
|
||||
peer.SendCultNet(new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
SubscriptionId = subscriptionId,
|
||||
ChangeKind = "removed",
|
||||
RecordKey = document.RecordKey,
|
||||
SchemaId = document.SchemaId
|
||||
});
|
||||
|
||||
private void Withdraw(SubscriptionKey key, bool sendRemovals, bool forgetRequest)
|
||||
{
|
||||
if (_subscriptions.TryRemove(key, out var subscription))
|
||||
subscription.Dispose();
|
||||
if (_projections.TryRemove(key, out var projection))
|
||||
{
|
||||
if (sendRemovals)
|
||||
{
|
||||
foreach (var delivered in projection.DeliveredBySourceRecordKey.Values)
|
||||
SendRemoval(key.Peer, key.Id, delivered);
|
||||
}
|
||||
if (projection.DemandActive && _requests.TryGetValue(key, out var activeRequest))
|
||||
PublishDemand(activeRequest, key, active: false);
|
||||
}
|
||||
if (forgetRequest)
|
||||
_requests.TryRemove(key, out _);
|
||||
}
|
||||
|
||||
private CultNetDatabaseChangeRawMessage? CreateAuthorizedChange(
|
||||
object change,
|
||||
CultNetDatabaseSubscribeMessage request,
|
||||
string subscriptionId,
|
||||
ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
return CreateChangeCore(change, request, subscriptionId, (recordKey, schemaId) =>
|
||||
_authorizeRecord?.Invoke(request, peer, recordKey, schemaId) != false);
|
||||
}
|
||||
|
||||
private CultNetDatabaseChangeRawMessage? CreateChange(
|
||||
object change,
|
||||
CultNetDatabaseSubscribeMessage request,
|
||||
string subscriptionId)
|
||||
{
|
||||
return CreateChangeCore(change, request, subscriptionId, (_, _) => true);
|
||||
}
|
||||
|
||||
private CultNetDatabaseChangeRawMessage? CreateChangeCore(
|
||||
object change,
|
||||
CultNetDatabaseSubscribeMessage request,
|
||||
string subscriptionId,
|
||||
Func<string, string, bool> authorizeRecord)
|
||||
{
|
||||
var changeType = change.GetType();
|
||||
var key = (CultRecordKey)(changeType.GetProperty("Key")?.GetValue(change) ?? new CultRecordKey(""));
|
||||
|
|
@ -206,6 +458,8 @@ namespace GameCult.Networking
|
|||
var schemaId = ResolveWireSchemaId(previous, (string?)changeType.GetProperty("SchemaId")?.GetValue(change) ?? "");
|
||||
if (!MatchesRequestedSchema(request.SchemaIds, previous, schemaId))
|
||||
return null;
|
||||
if (!authorizeRecord(key.Value, schemaId))
|
||||
return null;
|
||||
return new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
|
|
@ -219,6 +473,8 @@ namespace GameCult.Networking
|
|||
var raw = CreateRawRecord(key, document);
|
||||
if (!MatchesRequestedSchema(request.SchemaIds, document, raw.SchemaId))
|
||||
return null;
|
||||
if (!authorizeRecord(key.Value, raw.SchemaId))
|
||||
return null;
|
||||
return new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
|
|
@ -258,6 +514,27 @@ namespace GameCult.Networking
|
|||
return ((CultNetDocumentPutRawMessage)put!).Document;
|
||||
}
|
||||
|
||||
private sealed class SubscriptionProjectionState
|
||||
{
|
||||
public Dictionary<string, CultNetRawDocumentRecord> DeliveredBySourceRecordKey { get; } =
|
||||
new(StringComparer.Ordinal);
|
||||
public bool DemandActive { get; set; }
|
||||
}
|
||||
|
||||
private sealed class ProjectedSnapshot
|
||||
{
|
||||
public ProjectedSnapshot(Dictionary<string, CultNetRawDocumentRecord> bySourceRecordKey)
|
||||
{
|
||||
BySourceRecordKey = bySourceRecordKey;
|
||||
Documents = bySourceRecordKey.Values.ToArray();
|
||||
}
|
||||
|
||||
public static ProjectedSnapshot Empty { get; } =
|
||||
new(new Dictionary<string, CultNetRawDocumentRecord>(StringComparer.Ordinal));
|
||||
public Dictionary<string, CultNetRawDocumentRecord> BySourceRecordKey { get; }
|
||||
public CultNetRawDocumentRecord[] Documents { get; }
|
||||
}
|
||||
|
||||
private sealed class SubscriptionKey
|
||||
{
|
||||
public SubscriptionKey(ICultNetSchemaServerPeer peer, string id)
|
||||
|
|
|
|||
|
|
@ -164,6 +164,16 @@ namespace GameCult.Networking
|
|||
if (_disposed) return;
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
if (peer == null) throw new ArgumentNullException(nameof(peer));
|
||||
if (_sourceRuntimeId != null &&
|
||||
!string.Equals(request.TargetRuntimeId, _sourceRuntimeId, StringComparison.Ordinal))
|
||||
{
|
||||
peer.SendCultNet(Failure(
|
||||
request,
|
||||
"denied",
|
||||
"target-runtime-mismatch",
|
||||
$"Operation targeted runtime '{request.TargetRuntimeId ?? "(missing)"}', not '{_sourceRuntimeId}'."));
|
||||
return;
|
||||
}
|
||||
|
||||
Route route;
|
||||
try
|
||||
|
|
|
|||
|
|
@ -72,6 +72,8 @@ namespace GameCult.Networking
|
|||
CultNetSchemaVersions.SimulationConsensusCandidate => Deserialize<CultNetSimulationConsensusCandidateMessage>(payload),
|
||||
CultNetSchemaVersions.VerseCatalogRequest => Deserialize<CultMeshVerseCatalogRequestMessage>(payload),
|
||||
CultNetSchemaVersions.VerseCatalogResponse => Deserialize<CultMeshVerseCatalogResponseMessage>(payload),
|
||||
CultNetSchemaVersions.SessionOpen => Deserialize<CultMeshSessionOpenMessage>(payload),
|
||||
CultNetSchemaVersions.SessionAccepted => Deserialize<CultMeshSessionAcceptedMessage>(payload),
|
||||
CultNetSchemaVersions.PeerExchangeRequest => Deserialize<CultMeshPeerExchangeRequestMessage>(payload),
|
||||
CultNetSchemaVersions.PeerExchangeResponse => Deserialize<CultMeshPeerExchangeResponseMessage>(payload),
|
||||
CultNetSchemaVersions.ContentChunkRequest => Deserialize<CultMeshContentChunkRequestMessage>(payload),
|
||||
|
|
|
|||
|
|
@ -135,6 +135,10 @@ namespace GameCult.Networking
|
|||
/// CultMesh Verse catalog response contract identifier.
|
||||
/// </summary>
|
||||
public const string VerseCatalogResponse = "cultmesh.verse_catalog_response.v0";
|
||||
/// <summary>CultMesh session identity request contract identifier.</summary>
|
||||
public const string SessionOpen = "cultmesh.session_open.v2";
|
||||
/// <summary>CultMesh verified session identity response contract identifier.</summary>
|
||||
public const string SessionAccepted = "cultmesh.session_accepted.v2";
|
||||
/// <summary>
|
||||
/// CultMesh peer exchange request contract identifier.
|
||||
/// </summary>
|
||||
|
|
@ -1179,6 +1183,37 @@ namespace GameCult.Networking
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Requests an identity-bound CultMesh session before application traffic begins.</summary>
|
||||
[MessagePackObject]
|
||||
public class CultMeshSessionOpenMessage : ICultNetSchemaMessage
|
||||
{
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SessionOpen;
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
[Key("sourceRuntimeId")] public string SourceRuntimeId { get; set; } = string.Empty;
|
||||
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
|
||||
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
|
||||
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
|
||||
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
|
||||
[Key("clientNonce")] public string ClientNonce { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Accepts or rejects a CultMesh session with the server's actual identity.</summary>
|
||||
[MessagePackObject]
|
||||
public class CultMeshSessionAcceptedMessage : ICultNetSchemaMessage
|
||||
{
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.SessionAccepted;
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
[Key("accepted")] public bool Accepted { get; set; }
|
||||
[Key("verseId")] public string VerseId { get; set; } = string.Empty;
|
||||
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
|
||||
[Key("protocolId")] public string ProtocolId { get; set; } = string.Empty;
|
||||
[Key("routeGeneration")] public string RouteGeneration { get; set; } = string.Empty;
|
||||
[Key("clientNonce")] public string ClientNonce { get; set; } = string.Empty;
|
||||
[Key("providerKeyId")] public string ProviderKeyId { get; set; } = string.Empty;
|
||||
[Key("providerSignature")] public string ProviderSignature { get; set; } = string.Empty;
|
||||
[Key("error")] public string? Error { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests known CultMesh Verses from a peer.
|
||||
/// </summary>
|
||||
|
|
@ -1254,6 +1289,11 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
[Key("authorityRuntimeIds")] public string[] AuthorityRuntimeIds { get; set; } = Array.Empty<string>();
|
||||
/// <summary>
|
||||
/// Gets or sets exact authoritative-runtime route bindings. This is the
|
||||
/// routing authority; the parallel legacy arrays are projections only.
|
||||
/// </summary>
|
||||
[Key("authorityRoutes")] public CultMeshAuthorityRouteMessage[] AuthorityRoutes { get; set; } = Array.Empty<CultMeshAuthorityRouteMessage>();
|
||||
/// <summary>
|
||||
/// Gets or sets the parent Verse id for overlays or branches.
|
||||
/// </summary>
|
||||
[Key("parentVerseId")] public string? ParentVerseId { get; set; }
|
||||
|
|
@ -1263,6 +1303,30 @@ namespace GameCult.Networking
|
|||
[Key("description")] public string? Description { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Wire representation of one authority-bound CultMesh route.</summary>
|
||||
[MessagePackObject]
|
||||
public class CultMeshAuthorityRouteMessage
|
||||
{
|
||||
[Key("authorityRuntimeId")] public string AuthorityRuntimeId { get; set; } = string.Empty;
|
||||
[Key("endpoint")] public string Endpoint { get; set; } = string.Empty;
|
||||
[Key("protocolIds")] public string[] ProtocolIds { get; set; } = Array.Empty<string>();
|
||||
[Key("priority")] public int Priority { get; set; }
|
||||
[Key("generation")] public string Generation { get; set; } = string.Empty;
|
||||
[Key("certificate")] public CultMeshRouteCertificateMessage? Certificate { get; set; }
|
||||
}
|
||||
|
||||
[MessagePackObject]
|
||||
public class CultMeshRouteCertificateMessage
|
||||
{
|
||||
[Key("providerKeyId")] public string ProviderKeyId { get; set; } = string.Empty;
|
||||
[Key("providerPublicKeyX")] public string ProviderPublicKeyX { get; set; } = string.Empty;
|
||||
[Key("providerPublicKeyY")] public string ProviderPublicKeyY { get; set; } = string.Empty;
|
||||
[Key("odinKeyId")] public string OdinKeyId { get; set; } = string.Empty;
|
||||
[Key("issuedAtUnixMilliseconds")] public long IssuedAtUnixMilliseconds { get; set; }
|
||||
[Key("expiresAtUnixMilliseconds")] public long ExpiresAtUnixMilliseconds { get; set; }
|
||||
[Key("signature")] public string Signature { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wire representation of CultMesh Verse compatibility.
|
||||
/// </summary>
|
||||
|
|
|
|||
Loading…
Reference in a new issue