CultCache: [CultIndex] is unique at commit and load; [CultRole] names a selection role; replicas apply a commit's changes as one batch (#90)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 20m15s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 48s
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 20m15s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 48s
This commit is contained in:
parent
de8a062ab9
commit
7760219b7c
32 changed files with 1686 additions and 349 deletions
|
|
@ -315,6 +315,22 @@ namespace GameCult.Networking
|
|||
public CultNetSelectionCursorKey? CursorKey { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The typed changes (<see cref="CultNetDatabaseChange{T}"/> boxed) one cache commit made, in the order the cache admitted them.
|
||||
/// <see cref="Id"/> is opaque and unique among the commits of one database instance.
|
||||
/// </summary>
|
||||
public sealed class CultNetDatabaseCommit
|
||||
{
|
||||
public CultNetDatabaseCommit(string id, IReadOnlyList<object> changes)
|
||||
{
|
||||
Id = id;
|
||||
Changes = changes;
|
||||
}
|
||||
|
||||
public string Id { get; }
|
||||
public IReadOnlyList<object> Changes { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A typed domain change emitted by a CultNet database surface.
|
||||
/// </summary>
|
||||
|
|
@ -587,6 +603,7 @@ namespace GameCult.Networking
|
|||
private readonly Dictionary<(string SchemaId, string RecordKey), long> _lastWriteSequence =
|
||||
new();
|
||||
private readonly Subject<object> _changes = new();
|
||||
private readonly Subject<CultNetDatabaseCommit> _commits = new();
|
||||
private readonly IDisposable _cacheChanges;
|
||||
private readonly IDisposable _cacheJournal;
|
||||
// What a write door of this database knows about the change it is admitting and the cache does not: the wire
|
||||
|
|
@ -1148,6 +1165,17 @@ namespace GameCult.Networking
|
|||
return _changes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches changes as the cache commits that made them: one event per commit, after every change of it was published to
|
||||
/// <see cref="WatchAllChanges"/>. A consumer that forwards changes to a replica forwards a commit as a unit, so the replica
|
||||
/// can judge the result of the commit and not each record's intermediate state.
|
||||
/// </summary>
|
||||
public Observable<CultNetDatabaseCommit> WatchCommits()
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
return _commits;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches one record.
|
||||
/// </summary>
|
||||
|
|
@ -1215,6 +1243,7 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
_changes.Dispose();
|
||||
_commits.Dispose();
|
||||
}
|
||||
|
||||
// The cache is the one owner of "a change was committed"; the journal is this database's one decision point and its
|
||||
|
|
@ -1231,6 +1260,8 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
List<Exception>? failures = null;
|
||||
// One journal call is one admission, so one commit; its first Sequence names it.
|
||||
var commit = new CommitGroup(changes.Count == 0 ? "0" : changes[0].Sequence.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
List<CultNetBurnedSequence>? burned = null;
|
||||
List<Exception>? burnCauses = null;
|
||||
foreach (var change in changes)
|
||||
|
|
@ -1288,7 +1319,10 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
lock (_logGate)
|
||||
_stash[change.Sequence] = new Publication(documentType, kind, change.Key, descriptor.SchemaId, shard, change.Document, change.PreviousDocument);
|
||||
{
|
||||
_stash[change.Sequence] = new Publication(documentType, kind, change.Key, descriptor.SchemaId, shard, change.Document, change.PreviousDocument, commit);
|
||||
commit.Unpublished++;
|
||||
}
|
||||
}
|
||||
|
||||
// Every change is stashed and will be published; the writer hears of a failed log afterwards, in one exception.
|
||||
|
|
@ -1321,8 +1355,9 @@ namespace GameCult.Networking
|
|||
Publish(publication);
|
||||
}
|
||||
|
||||
private void Publish(Publication publication) =>
|
||||
PublishUntyped(
|
||||
private void Publish(Publication publication)
|
||||
{
|
||||
var change = PublishUntyped(
|
||||
publication.DocumentType,
|
||||
publication.Kind,
|
||||
publication.Key,
|
||||
|
|
@ -1330,6 +1365,19 @@ namespace GameCult.Networking
|
|||
publication.Shard,
|
||||
publication.Document,
|
||||
publication.PreviousDocument);
|
||||
CultNetDatabaseCommit? finished = null;
|
||||
lock (_logGate)
|
||||
{
|
||||
var commit = publication.Commit;
|
||||
if (change != null)
|
||||
commit.Published.Add(change);
|
||||
if (--commit.Unpublished == 0 && commit.Published.Count > 0)
|
||||
finished = new CultNetDatabaseCommit(commit.Id, commit.Published.ToArray());
|
||||
}
|
||||
|
||||
if (finished != null)
|
||||
_commits.OnNext(finished);
|
||||
}
|
||||
|
||||
private void RecordReplicatedEntry(
|
||||
CultNetShardDescriptor shard,
|
||||
|
|
@ -1467,8 +1515,10 @@ namespace GameCult.Networking
|
|||
string schemaId,
|
||||
CultNetShardDescriptor shard,
|
||||
object? document,
|
||||
object? previousDocument)
|
||||
object? previousDocument,
|
||||
CommitGroup commit)
|
||||
{
|
||||
Commit = commit;
|
||||
DocumentType = documentType;
|
||||
Kind = kind;
|
||||
Key = key;
|
||||
|
|
@ -1485,6 +1535,16 @@ namespace GameCult.Networking
|
|||
public CultNetShardDescriptor Shard { get; }
|
||||
public object? Document { get; }
|
||||
public object? PreviousDocument { get; }
|
||||
public CommitGroup Commit { get; }
|
||||
}
|
||||
|
||||
// The changes of one cache admission, counted down as they are published. Guarded by _logGate.
|
||||
private sealed class CommitGroup
|
||||
{
|
||||
public CommitGroup(string id) => Id = id;
|
||||
public string Id { get; }
|
||||
public int Unpublished { get; set; }
|
||||
public List<object> Published { get; } = new();
|
||||
}
|
||||
|
||||
private sealed class DoorContext
|
||||
|
|
@ -1964,7 +2024,7 @@ namespace GameCult.Networking
|
|||
return $"{schemaId}:{key.Value}";
|
||||
}
|
||||
|
||||
private void PublishUntyped(
|
||||
private object? PublishUntyped(
|
||||
Type documentType,
|
||||
CultNetDatabaseChangeKind kind,
|
||||
CultRecordKey key,
|
||||
|
|
@ -1987,6 +2047,8 @@ namespace GameCult.Networking
|
|||
{
|
||||
_changes.OnNext(change);
|
||||
}
|
||||
|
||||
return change;
|
||||
}
|
||||
|
||||
// No shard owns a schema and key that no descriptor matches, and nothing is written to one: every write path refuses.
|
||||
|
|
|
|||
|
|
@ -765,14 +765,41 @@ namespace GameCult.Networking
|
|||
{
|
||||
// Keys this subscriber only ever received as a refusal: it was never given them as records.
|
||||
var refused = new HashSet<string>(StringComparer.Ordinal);
|
||||
return _database.WatchAllChanges().Subscribe(change =>
|
||||
return _database.WatchCommits().Subscribe(commit =>
|
||||
{
|
||||
var outbound = DeliverChange(change, subscriptionId, selection, refused, error => peer.SendCultNet(error));
|
||||
if (outbound != null)
|
||||
peer.SendCultNet(outbound);
|
||||
foreach (var message in DeliverCommit(commit, subscriptionId, selection, refused, error => peer.SendCultNet(error)))
|
||||
peer.SendCultNet(message);
|
||||
});
|
||||
}
|
||||
|
||||
// One subscriber's view of one commit. Its changes go out together, tagged with the commit, so a replica applies them as one.
|
||||
internal IReadOnlyList<CultNetDatabaseChangeRawMessage> DeliverCommit(
|
||||
CultNetDatabaseCommit commit,
|
||||
string subscriptionId,
|
||||
CultNetSelection selection,
|
||||
HashSet<string> refused,
|
||||
Action<CultNetErrorMessage> sendError)
|
||||
{
|
||||
var outbound = new List<CultNetDatabaseChangeRawMessage>();
|
||||
foreach (var change in commit.Changes)
|
||||
{
|
||||
var message = DeliverChange(change, subscriptionId, selection, refused, sendError);
|
||||
if (message != null)
|
||||
outbound.Add(message);
|
||||
}
|
||||
|
||||
if (outbound.Count > 1)
|
||||
{
|
||||
foreach (var message in outbound)
|
||||
{
|
||||
message.CommitId = commit.Id;
|
||||
message.CommitCount = outbound.Count;
|
||||
}
|
||||
}
|
||||
|
||||
return outbound;
|
||||
}
|
||||
|
||||
// One subscriber's view of one change. A variant is not a record CultNet can carry (Q6): the subscriber is told, by key, and
|
||||
// is not later told the variant was removed, because it never held it.
|
||||
internal CultNetDatabaseChangeRawMessage? DeliverChange(
|
||||
|
|
|
|||
|
|
@ -29,6 +29,14 @@ namespace GameCult.Networking
|
|||
private readonly ConcurrentDictionary<string, PendingSubscription> _initialSnapshots = new();
|
||||
private readonly ConcurrentDictionary<string, CultNetDatabaseSubscriptionDeliveryMode> _deliveryModes =
|
||||
new(StringComparer.Ordinal);
|
||||
// Changes of a commit that has not fully arrived, by subscription and commit id.
|
||||
// Guarded by its own lock: the queue fills it, Unsubscribe and Dispose evict. A commit that does not complete is bounded
|
||||
// by MaxPendingCommits and by MaxBufferedChanges, and a violation faults the client.
|
||||
private const int MaxPendingCommits = 64;
|
||||
// Policy: the most changes the incomplete commits may announce between them, the bound on what the buffer can hold. It
|
||||
// sits far above any commit a source makes; a commit that announces more than this could not be held at all.
|
||||
private const int MaxBufferedChanges = 1_000_000;
|
||||
private readonly Dictionary<(string SubscriptionId, string CommitId), PendingCommit> _commits = new();
|
||||
private readonly object _queueLock = new();
|
||||
private Task _queue = Task.CompletedTask;
|
||||
private bool _disposed;
|
||||
|
|
@ -48,6 +56,15 @@ namespace GameCult.Networking
|
|||
/// <summary>Raised after a live change has been applied to the local typed cache.</summary>
|
||||
public event Action<CultNetReplicatedDocumentChange>? Changed;
|
||||
|
||||
/// <summary>
|
||||
/// Raised when the local cache refuses a replicated commit. The replica then differs from its source; the client applies
|
||||
/// no further changes and reports <see cref="Fault"/> until it is replaced by a new subscription.
|
||||
/// </summary>
|
||||
public event Action<Exception>? Faulted;
|
||||
|
||||
/// <summary>The refusal that stopped replication, or null while the replica is intact.</summary>
|
||||
public Exception? Fault { get; private set; }
|
||||
|
||||
/// <summary>Gets the local reactive cache receiving replicated documents.</summary>
|
||||
public CultCache Cache => _cache;
|
||||
|
||||
|
|
@ -109,6 +126,8 @@ namespace GameCult.Networking
|
|||
CultNetDatabaseSubscriptionDeliveryMode deliveryMode = CultNetDatabaseSubscriptionDeliveryMode.ReplicateToCache)
|
||||
{
|
||||
if (_disposed) throw new ObjectDisposedException(nameof(CultNetDatabaseSubscriptionClient));
|
||||
if (Fault != null)
|
||||
throw new InvalidOperationException("The replica refused a commit and differs from its source; subscribe with a new client.", Fault);
|
||||
if (!_client.Connected) throw new InvalidOperationException("CultNet schema client must be connected before subscribing.");
|
||||
if (string.IsNullOrWhiteSpace(subscriptionId)) throw new ArgumentException("Subscription id is required.", nameof(subscriptionId));
|
||||
|
||||
|
|
@ -166,6 +185,9 @@ namespace GameCult.Networking
|
|||
if (_disposed) return;
|
||||
if (string.IsNullOrWhiteSpace(subscriptionId)) throw new ArgumentException("Subscription id is required.", nameof(subscriptionId));
|
||||
_deliveryModes.TryRemove(subscriptionId, out _);
|
||||
lock (_commits)
|
||||
foreach (var held in _commits.Keys.Where(key => key.SubscriptionId == subscriptionId).ToArray())
|
||||
_commits.Remove(held);
|
||||
_client.SendCultNet(new CultNetDatabaseUnsubscribeMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
|
|
@ -181,6 +203,8 @@ namespace GameCult.Networking
|
|||
pending.Completion.TrySetException(new ObjectDisposedException(nameof(CultNetDatabaseSubscriptionClient)));
|
||||
_initialSnapshots.Clear();
|
||||
_deliveryModes.Clear();
|
||||
lock (_commits)
|
||||
_commits.Clear();
|
||||
_client.Dispose();
|
||||
}
|
||||
|
||||
|
|
@ -211,48 +235,111 @@ namespace GameCult.Networking
|
|||
|
||||
private void HandleChange(CultNetDatabaseChangeRawMessage message)
|
||||
{
|
||||
Enqueue(async () =>
|
||||
Enqueue(() =>
|
||||
{
|
||||
var deliveryMode = _deliveryModes.TryGetValue(message.SubscriptionId, out var configured)
|
||||
? configured
|
||||
: CultNetDatabaseSubscriptionDeliveryMode.ReplicateToCache;
|
||||
if (string.Equals(message.ChangeKind, "removed", StringComparison.Ordinal))
|
||||
// Live delivery applies nothing, so there is no commit to judge; each change is reported as it arrives.
|
||||
if (deliveryMode != CultNetDatabaseSubscriptionDeliveryMode.ReplicateToCache || message.CommitId == null || !(message.CommitCount > 1))
|
||||
return Apply(deliveryMode, new[] { message });
|
||||
|
||||
// The commit's other changes follow on this connection; the replica applies them as one commit.
|
||||
// A straggler of a subscription that was ended, or never made, is not buffered.
|
||||
if (!_deliveryModes.ContainsKey(message.SubscriptionId))
|
||||
return Task.CompletedTask;
|
||||
var held = (message.SubscriptionId, message.CommitId);
|
||||
PendingCommit? pending;
|
||||
lock (_commits)
|
||||
{
|
||||
if (deliveryMode == CultNetDatabaseSubscriptionDeliveryMode.ReplicateToCache)
|
||||
await DeleteAsync(message).ConfigureAwait(false);
|
||||
Changed?.Invoke(new CultNetReplicatedDocumentChange(
|
||||
message.SubscriptionId,
|
||||
"removed",
|
||||
message.RecordKey ?? string.Empty,
|
||||
message.SchemaId ?? string.Empty,
|
||||
null));
|
||||
return;
|
||||
if (Fault != null)
|
||||
return Task.CompletedTask;
|
||||
var count = message.CommitCount!.Value;
|
||||
var refusal = !_commits.TryGetValue(held, out pending)
|
||||
? (_commits.Count >= MaxPendingCommits
|
||||
? $"more than {MaxPendingCommits} commits are incomplete at once"
|
||||
: (long)count + _commits.Sum(entry => (long)entry.Value.Announced) > MaxBufferedChanges
|
||||
? $"commit '{message.CommitId}' announces {count} changes; the incomplete commits may announce {MaxBufferedChanges} between them"
|
||||
: null)
|
||||
: pending.Announced != count
|
||||
? $"commit '{message.CommitId}' announces {pending.Announced} and {count} changes"
|
||||
: pending.Ids.Contains(message.MessageId)
|
||||
? $"commit '{message.CommitId}' delivered message '{message.MessageId}' twice"
|
||||
: null;
|
||||
if (refusal != null)
|
||||
{
|
||||
Break(new InvalidOperationException($"CultNet subscription '{message.SubscriptionId}': {refusal}."));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (!_commits.TryGetValue(held, out pending))
|
||||
_commits[held] = pending = new PendingCommit(count);
|
||||
pending.Ids.Add(message.MessageId);
|
||||
pending.Messages.Add(message);
|
||||
if (pending.Messages.Count < count)
|
||||
return Task.CompletedTask;
|
||||
_commits.Remove(held);
|
||||
}
|
||||
|
||||
if (message.Document == null) return;
|
||||
var document = deliveryMode == CultNetDatabaseSubscriptionDeliveryMode.Live
|
||||
? _documents.DeserializeRawDocument(message.Document)
|
||||
: await _documents.ApplyRawDocumentPutMessageAsync(
|
||||
_cache,
|
||||
new CultNetDocumentPutRawMessage
|
||||
{
|
||||
MessageId = message.MessageId,
|
||||
Document = message.Document
|
||||
}).ConfigureAwait(false);
|
||||
Changed?.Invoke(new CultNetReplicatedDocumentChange(
|
||||
message.SubscriptionId,
|
||||
message.ChangeKind,
|
||||
message.Document.RecordKey,
|
||||
message.Document.SchemaId,
|
||||
document));
|
||||
return Apply(deliveryMode, pending.Messages);
|
||||
});
|
||||
}
|
||||
|
||||
private Task DeleteAsync(CultNetDatabaseChangeRawMessage message)
|
||||
private sealed class PendingCommit
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message.RecordKey) || string.IsNullOrWhiteSpace(message.SchemaId)) return Task.CompletedTask;
|
||||
_documents.ResolveDescriptorForSchemaId(message.SchemaId!);
|
||||
_cache.Remove(new CultRecordKey(message.RecordKey!));
|
||||
public PendingCommit(int announced) => Announced = announced;
|
||||
public int Announced { get; }
|
||||
public List<CultNetDatabaseChangeRawMessage> Messages { get; } = new();
|
||||
public HashSet<string> Ids { get; } = new(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
// The replica no longer matches its source: say so once, drop what was waiting, and apply nothing more.
|
||||
private void Break(Exception error)
|
||||
{
|
||||
lock (_commits)
|
||||
{
|
||||
if (Fault != null)
|
||||
return;
|
||||
Fault = error;
|
||||
_commits.Clear();
|
||||
}
|
||||
|
||||
Faulted?.Invoke(error);
|
||||
}
|
||||
|
||||
private Task Apply(CultNetDatabaseSubscriptionDeliveryMode deliveryMode, IReadOnlyList<CultNetDatabaseChangeRawMessage> changes)
|
||||
{
|
||||
// A replica that refused a commit no longer matches its source. Applying later commits on top would hide that, so
|
||||
// nothing more is applied: the fault is surfaced and the replica is rebuilt by subscribing again.
|
||||
if (Fault != null)
|
||||
return Task.CompletedTask;
|
||||
IReadOnlyList<object?> applied;
|
||||
try
|
||||
{
|
||||
applied = deliveryMode == CultNetDatabaseSubscriptionDeliveryMode.Live
|
||||
? changes.Select(change => change.Document == null ? null : _documents.DeserializeRawDocument(change.Document)).ToArray()
|
||||
: _documents.ApplyRawChangesAsOneCommit(_cache, changes);
|
||||
}
|
||||
catch (Exception error)
|
||||
{
|
||||
Break(error);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
for (var index = 0; index < changes.Count; index++)
|
||||
{
|
||||
var change = changes[index];
|
||||
var removed = string.Equals(change.ChangeKind, "removed", StringComparison.Ordinal);
|
||||
if (!removed && change.Document == null)
|
||||
continue;
|
||||
Changed?.Invoke(new CultNetReplicatedDocumentChange(
|
||||
change.SubscriptionId,
|
||||
change.ChangeKind,
|
||||
removed ? change.RecordKey ?? string.Empty : change.Document!.RecordKey,
|
||||
removed ? change.SchemaId ?? string.Empty : change.Document!.SchemaId,
|
||||
removed ? null : applied[index]));
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -300,50 +300,76 @@ namespace GameCult.Networking
|
|||
SubscriptionKey key)
|
||||
{
|
||||
var legacyRequest = request.ToLegacyShape(subscriptionId);
|
||||
return _database.WatchAllChanges().Subscribe(change =>
|
||||
return _database.WatchCommits().Subscribe(commit =>
|
||||
{
|
||||
lock (_lifecycleGate)
|
||||
{
|
||||
if (_disposed || !_requests.ContainsKey(key) || !_projections.TryGetValue(key, out var projection))
|
||||
return;
|
||||
if (_authorizeRequest?.Invoke(legacyRequest, peer) == false)
|
||||
{
|
||||
Reconcile(key, request);
|
||||
return;
|
||||
}
|
||||
|
||||
// D6: cites/cited are set-dependent - a change to row B can change whether row A
|
||||
// matches - so a hop-bearing selection runs the full diff-against-delivered
|
||||
// reconcile on every change instead of the single-row fast path.
|
||||
if (request.Selection.HasHop)
|
||||
{
|
||||
Reconcile(key, request);
|
||||
return;
|
||||
}
|
||||
|
||||
var sourceRecordKey = ResolveChangeRecordKey(change);
|
||||
CultNetRawDocumentRecord? matched;
|
||||
// What this subscription sends for the commit is held and sent together, tagged with the commit, so the replica
|
||||
// applies it as one commit and judges the result.
|
||||
var outbox = _outbox = new CommitOutbox(commit.Id);
|
||||
try
|
||||
{
|
||||
matched = CreateMatchedRecord(change, request, peer);
|
||||
ForwardCommit(commit, request, key, projection, legacyRequest, peer, subscriptionId);
|
||||
}
|
||||
catch (NotSupportedException refusal)
|
||||
finally
|
||||
{
|
||||
// Q6: a variant is not a record CultNet can carry; the subscriber that would have received it is told, by key.
|
||||
peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message));
|
||||
return;
|
||||
_outbox = null;
|
||||
outbox.Send(peer);
|
||||
}
|
||||
|
||||
ApplyProjectedChange(
|
||||
projection,
|
||||
sourceRecordKey,
|
||||
matched,
|
||||
peer,
|
||||
subscriptionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ForwardCommit(
|
||||
CultNetDatabaseCommit commit,
|
||||
SubscriptionRequest request,
|
||||
SubscriptionKey key,
|
||||
SubscriptionProjectionState projection,
|
||||
CultNetDatabaseSubscribeMessage legacyRequest,
|
||||
ICultNetSchemaServerPeer peer,
|
||||
string subscriptionId)
|
||||
{
|
||||
if (_authorizeRequest?.Invoke(legacyRequest, peer) == false)
|
||||
{
|
||||
Reconcile(key, request);
|
||||
return;
|
||||
}
|
||||
|
||||
// D6: cites/cited are set-dependent - a change to row B can change whether row A
|
||||
// matches - so a hop-bearing selection runs the full diff-against-delivered
|
||||
// reconcile once per commit instead of the single-row fast path.
|
||||
if (request.Selection.HasHop)
|
||||
{
|
||||
Reconcile(key, request);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var change in commit.Changes)
|
||||
{
|
||||
var sourceRecordKey = ResolveChangeRecordKey(change);
|
||||
CultNetRawDocumentRecord? matched;
|
||||
try
|
||||
{
|
||||
matched = CreateMatchedRecord(change, request, peer);
|
||||
}
|
||||
catch (NotSupportedException refusal)
|
||||
{
|
||||
// Q6: a variant is not a record CultNet can carry; the subscriber that would have received it is told, by key.
|
||||
peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message));
|
||||
continue;
|
||||
}
|
||||
|
||||
ApplyProjectedChange(
|
||||
projection,
|
||||
sourceRecordKey,
|
||||
matched,
|
||||
peer,
|
||||
subscriptionId);
|
||||
}
|
||||
}
|
||||
|
||||
private void Reconcile(SubscriptionKey key, SubscriptionRequest request)
|
||||
{
|
||||
if (!_projections.TryGetValue(key, out var projection)) return;
|
||||
|
|
@ -487,12 +513,15 @@ namespace GameCult.Networking
|
|||
string.Equals(left.SourceAgentId, right.SourceAgentId, StringComparison.Ordinal) &&
|
||||
string.Equals(left.SourceRole, right.SourceRole, StringComparison.Ordinal);
|
||||
|
||||
private static void SendUpsert(
|
||||
// The commit being forwarded, under _lifecycleGate: the change messages it produces are held here, not sent one by one.
|
||||
private CommitOutbox? _outbox;
|
||||
|
||||
private void SendUpsert(
|
||||
ICultNetSchemaServerPeer peer,
|
||||
string subscriptionId,
|
||||
CultNetRawDocumentRecord document,
|
||||
bool added) =>
|
||||
peer.SendCultNet(new CultNetDatabaseChangeRawMessage
|
||||
Deliver(peer, new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
SubscriptionId = subscriptionId,
|
||||
|
|
@ -500,11 +529,11 @@ namespace GameCult.Networking
|
|||
Document = document
|
||||
});
|
||||
|
||||
private static void SendRemoval(
|
||||
private void SendRemoval(
|
||||
ICultNetSchemaServerPeer peer,
|
||||
string subscriptionId,
|
||||
CultNetRawDocumentRecord document) =>
|
||||
peer.SendCultNet(new CultNetDatabaseChangeRawMessage
|
||||
Deliver(peer, new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
SubscriptionId = subscriptionId,
|
||||
|
|
@ -513,6 +542,38 @@ namespace GameCult.Networking
|
|||
SchemaId = document.SchemaId
|
||||
});
|
||||
|
||||
private void Deliver(ICultNetSchemaServerPeer peer, CultNetDatabaseChangeRawMessage message)
|
||||
{
|
||||
if (_outbox is { } outbox)
|
||||
outbox.Messages.Add(message);
|
||||
else
|
||||
peer.SendCultNet(message);
|
||||
}
|
||||
|
||||
private sealed class CommitOutbox
|
||||
{
|
||||
private readonly string _commitId;
|
||||
|
||||
public CommitOutbox(string commitId) => _commitId = commitId;
|
||||
|
||||
public List<CultNetDatabaseChangeRawMessage> Messages { get; } = new();
|
||||
|
||||
public void Send(ICultNetSchemaServerPeer peer)
|
||||
{
|
||||
if (Messages.Count > 1)
|
||||
{
|
||||
foreach (var message in Messages)
|
||||
{
|
||||
message.CommitId = _commitId;
|
||||
message.CommitCount = Messages.Count;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var message in Messages)
|
||||
peer.SendCultNet(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void Withdraw(SubscriptionKey key, bool sendRemovals, bool forgetRequest)
|
||||
{
|
||||
if (_subscriptions.TryRemove(key, out var subscription))
|
||||
|
|
|
|||
|
|
@ -722,6 +722,49 @@ namespace GameCult.Networking
|
|||
return document;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies change messages to a cache as one commit, so the cache judges the result of the changes together and not the
|
||||
/// state between them. Returns the applied document of each message, null for a removal. A refusal by the cache throws
|
||||
/// and nothing is applied.
|
||||
/// </summary>
|
||||
internal IReadOnlyList<object?> ApplyRawChangesAsOneCommit(
|
||||
CultCache cache,
|
||||
IReadOnlyList<CultNetDatabaseChangeRawMessage> changes)
|
||||
{
|
||||
var applied = new object?[changes.Count];
|
||||
var staged = new List<(Type? Type, object? Document, CultRecordKey Key)>(changes.Count);
|
||||
for (var index = 0; index < changes.Count; index++)
|
||||
{
|
||||
var change = changes[index];
|
||||
if (string.Equals(change.ChangeKind, "removed", StringComparison.Ordinal))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(change.RecordKey) || string.IsNullOrWhiteSpace(change.SchemaId))
|
||||
continue;
|
||||
ResolveDescriptorForSchemaId(change.SchemaId!);
|
||||
staged.Add((null, null, new CultRecordKey(change.RecordKey!)));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (change.Document == null)
|
||||
continue;
|
||||
var document = DeserializeRawDocument(change.Document);
|
||||
applied[index] = document;
|
||||
staged.Add((ResolveDescriptorForRawDocument(change.Document).DocumentType, document, new CultRecordKey(change.Document.RecordKey)));
|
||||
}
|
||||
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
foreach (var (type, document, key) in staged)
|
||||
{
|
||||
if (type == null)
|
||||
batch.Remove(key);
|
||||
else
|
||||
batch.Upsert(type, document!, key);
|
||||
}
|
||||
});
|
||||
return applied;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decodes one validated raw document without materializing it in a CultCache replica.
|
||||
/// Use this for ephemeral reactive subscriptions whose callback is the consumer.
|
||||
|
|
@ -754,25 +797,22 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies all documents from a raw snapshot response.
|
||||
/// Applies all documents from a raw snapshot response as one commit, so a snapshot that moves a unique-index value
|
||||
/// between records is judged on its result.
|
||||
/// </summary>
|
||||
public async Task<IReadOnlyList<object>> ApplyRawSnapshotResponseAsync(
|
||||
public Task<IReadOnlyList<object>> ApplyRawSnapshotResponseAsync(
|
||||
CultCache cache,
|
||||
CultNetSnapshotResponseRawMessage response)
|
||||
{
|
||||
var applied = new List<object>(response.Documents.Length);
|
||||
foreach (var document in response.Documents)
|
||||
{
|
||||
applied.Add(await ApplyRawDocumentPutMessageAsync(
|
||||
cache,
|
||||
new CultNetDocumentPutRawMessage
|
||||
{
|
||||
MessageId = response.MessageId,
|
||||
Document = document
|
||||
}).ConfigureAwait(false));
|
||||
}
|
||||
|
||||
return applied;
|
||||
var applied = ApplyRawChangesAsOneCommit(
|
||||
cache,
|
||||
response.Documents.Select(document => new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
SubscriptionId = response.MessageId,
|
||||
ChangeKind = "added",
|
||||
Document = document
|
||||
}).ToArray());
|
||||
return Task.FromResult<IReadOnlyList<object>>(applied.Select(document => document!).ToArray());
|
||||
}
|
||||
|
||||
internal CultDocumentDescriptor ResolveDescriptorForRawDocument(CultNetRawDocumentRecord document)
|
||||
|
|
|
|||
|
|
@ -1179,6 +1179,17 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the deleted schema id for removed changes.
|
||||
/// </summary>
|
||||
[Key("schemaId")] public string? SchemaId { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the identity of the cache commit this change belongs to. Optional and additive: a peer that does not
|
||||
/// know the field ignores it and applies the change alone. Opaque to the receiver; equal ids on one subscription
|
||||
/// name changes of one commit.
|
||||
/// </summary>
|
||||
[Key("commitId")] public string? CommitId { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets how many change messages of this commit this subscription carries. Set with
|
||||
/// <see cref="CommitId"/> when that is more than one; the receiver applies the commit once all have arrived.
|
||||
/// </summary>
|
||||
[Key("commitCount")] public int? CommitCount { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
Loading…
Reference in a new issue