Apply CultNet shard logs on replicas
This commit is contained in:
parent
a900687751
commit
e8b2322420
5 changed files with 354 additions and 21 deletions
|
|
@ -166,14 +166,16 @@ Shard catalog exchange now exists:
|
|||
endpoints
|
||||
- in-memory per-shard mutation logs and catch-up by last seen sequence
|
||||
- wire-level shard mutation log catch-up with raw put/delete entries
|
||||
- replica-side application of shard log responses with epoch checks, gap
|
||||
rejection, and idempotent replay
|
||||
|
||||
## Next Cut
|
||||
|
||||
Build durable replica catch-up:
|
||||
Build durable replica catch-up loops:
|
||||
|
||||
- persist per-shard logs and last-applied replica sequence
|
||||
- define the snapshot fallback boundary for compacted history
|
||||
- add a replica-side apply loop for shard log responses
|
||||
- add a background pull loop from catalog-advertised primary endpoints
|
||||
|
||||
That is the next foundation needed before membership, Raft-style failover, or
|
||||
CRDT policy work can be honest.
|
||||
|
|
|
|||
|
|
@ -52,13 +52,15 @@ Implemented:
|
|||
- mutation-log catch-up by last seen sequence
|
||||
- wire-level shard log request/response messages
|
||||
- raw put/delete representation for accepted mutation-log entries
|
||||
- replica-side shard log application with epoch checks, gap rejection, and
|
||||
idempotent replay
|
||||
|
||||
Not implemented yet:
|
||||
|
||||
- membership/failure detection
|
||||
- leader election or automatic shard failover
|
||||
- durable log persistence and compaction
|
||||
- replica-side log application loop
|
||||
- background replica pull loops
|
||||
- declared CRDT merge policies
|
||||
|
||||
## Live Invariants
|
||||
|
|
@ -75,15 +77,14 @@ Not implemented yet:
|
|||
|
||||
## Next Coherent Slice
|
||||
|
||||
Add durable log storage and replica application:
|
||||
Add durable log storage and background replica pull loops:
|
||||
|
||||
- persist per-shard mutation logs instead of keeping them only in memory
|
||||
- define the compaction boundary that turns old log reads into snapshot reads
|
||||
- apply `cultnet.shard_log_response.v0` entries on replicas through
|
||||
`CultNetDatabase`
|
||||
- track last applied sequence per shard
|
||||
- store last applied sequence per shard across restarts
|
||||
- let replicas periodically pull from primary endpoints in the shard catalog
|
||||
|
||||
The log is now wire-readable. The next useful layer is making a replica consume
|
||||
that stream durably enough that restart/reconnect behavior can be explained
|
||||
without hand waving. Membership and leader election should wait until basic
|
||||
replica catch-up is boring.
|
||||
The log is now wire-readable and replicas can apply it explicitly. The next
|
||||
useful layer is making that state survive restart and giving replicas a pull
|
||||
loop. Membership and leader election should wait until basic replica catch-up is
|
||||
boring.
|
||||
|
|
|
|||
|
|
@ -332,6 +332,7 @@ namespace GameCult.Networking
|
|||
private readonly Dictionary<string, List<CultNetShardMutationLogEntry>> _mutationLogs =
|
||||
new(StringComparer.Ordinal);
|
||||
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 bool _disposed;
|
||||
|
||||
|
|
@ -387,6 +388,18 @@ namespace GameCult.Networking
|
|||
return query.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last replicated sequence applied for a shard.
|
||||
/// </summary>
|
||||
public long GetAppliedShardSequence(string shardId)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (string.IsNullOrWhiteSpace(shardId)) throw new ArgumentException("Value must be non-empty.", nameof(shardId));
|
||||
return _appliedShardSequences.TryGetValue(shardId, out var sequence)
|
||||
? sequence
|
||||
: 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a shard catalog response for optional schema/key filters.
|
||||
/// </summary>
|
||||
|
|
@ -575,6 +588,57 @@ namespace GameCult.Networking
|
|||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies committed shard-log entries from an authoritative peer.
|
||||
/// </summary>
|
||||
public async Task<long> ApplyShardLogResponseAsync(CultNetShardLogResponseMessage response)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (response == null) throw new ArgumentNullException(nameof(response));
|
||||
if (response.ResyncRequired)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Shard '{response.ShardId}' requires snapshot resync before log application: {response.Reason ?? "unspecified"}.");
|
||||
}
|
||||
|
||||
var shard = _shards.FirstOrDefault(candidate =>
|
||||
string.Equals(candidate.ShardId, response.ShardId, StringComparison.Ordinal));
|
||||
if (shard == null)
|
||||
{
|
||||
throw new InvalidOperationException($"Shard '{response.ShardId}' is not known by this database.");
|
||||
}
|
||||
|
||||
if (response.ShardEpoch != shard.Epoch)
|
||||
{
|
||||
throw new CultNetShardAuthorityException(
|
||||
shard,
|
||||
$"Shard '{shard.ShardId}' is at epoch {shard.Epoch}, not response epoch {response.ShardEpoch}.",
|
||||
"stale_epoch");
|
||||
}
|
||||
|
||||
var lastApplied = GetAppliedShardSequence(response.ShardId);
|
||||
var orderedEntries = response.Entries.OrderBy(entry => entry.Sequence).ToArray();
|
||||
foreach (var entry in orderedEntries)
|
||||
{
|
||||
if (entry.Sequence <= lastApplied)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.Sequence != lastApplied + 1)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Shard '{response.ShardId}' log has a gap. Expected sequence {lastApplied + 1}, received {entry.Sequence}.");
|
||||
}
|
||||
|
||||
await ApplyCommittedShardLogEntryAsync(shard, entry).ConfigureAwait(false);
|
||||
lastApplied = entry.Sequence;
|
||||
_appliedShardSequences[response.ShardId] = lastApplied;
|
||||
}
|
||||
|
||||
return lastApplied;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Watches all changes assignable to the requested document type.
|
||||
/// </summary>
|
||||
|
|
@ -711,12 +775,8 @@ namespace GameCult.Networking
|
|||
object? document,
|
||||
object? previousDocument)
|
||||
{
|
||||
var sequence = _nextLogSequences.TryGetValue(shard.ShardId, out var next)
|
||||
? next
|
||||
: 1;
|
||||
_nextLogSequences[shard.ShardId] = sequence + 1;
|
||||
|
||||
var entry = new CultNetShardMutationLogEntry(
|
||||
var sequence = NextMutationLogSequence(shard.ShardId);
|
||||
RecordMutationLogEntry(new CultNetShardMutationLogEntry(
|
||||
shard.ShardId,
|
||||
shard.Epoch,
|
||||
sequence,
|
||||
|
|
@ -725,15 +785,160 @@ namespace GameCult.Networking
|
|||
schemaId,
|
||||
key,
|
||||
document,
|
||||
previousDocument);
|
||||
previousDocument));
|
||||
}
|
||||
|
||||
if (!_mutationLogs.TryGetValue(shard.ShardId, out var entries))
|
||||
private void RecordMutationLogEntry(CultNetShardMutationLogEntry entry)
|
||||
{
|
||||
if (!_mutationLogs.TryGetValue(entry.ShardId, out var entries))
|
||||
{
|
||||
entries = new List<CultNetShardMutationLogEntry>();
|
||||
_mutationLogs[shard.ShardId] = entries;
|
||||
_mutationLogs[entry.ShardId] = entries;
|
||||
}
|
||||
|
||||
entries.Add(entry);
|
||||
if (!_nextLogSequences.TryGetValue(entry.ShardId, out var next) ||
|
||||
next <= entry.Sequence)
|
||||
{
|
||||
_nextLogSequences[entry.ShardId] = entry.Sequence + 1;
|
||||
}
|
||||
}
|
||||
|
||||
private long NextMutationLogSequence(string shardId)
|
||||
{
|
||||
var sequence = _nextLogSequences.TryGetValue(shardId, out var next)
|
||||
? next
|
||||
: 1;
|
||||
_nextLogSequences[shardId] = sequence + 1;
|
||||
return sequence;
|
||||
}
|
||||
|
||||
private async Task ApplyCommittedShardLogEntryAsync(
|
||||
CultNetShardDescriptor shard,
|
||||
CultNetShardLogEntryMessage entry)
|
||||
{
|
||||
if (entry.Put != null)
|
||||
{
|
||||
await ApplyCommittedPutAsync(shard, entry).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (entry.Delete != null)
|
||||
{
|
||||
ApplyCommittedDelete(shard, entry);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new InvalidOperationException(
|
||||
$"Shard '{shard.ShardId}' log entry {entry.Sequence} has no put or delete payload.");
|
||||
}
|
||||
|
||||
private async Task ApplyCommittedPutAsync(
|
||||
CultNetShardDescriptor shard,
|
||||
CultNetShardLogEntryMessage entry)
|
||||
{
|
||||
var message = entry.Put!;
|
||||
if (message.Document == null)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Shard '{shard.ShardId}' log entry {entry.Sequence} put is missing its document payload.");
|
||||
}
|
||||
|
||||
if (!string.Equals(message.ShardId, shard.ShardId, StringComparison.Ordinal) ||
|
||||
message.ShardEpoch != shard.Epoch)
|
||||
{
|
||||
throw new CultNetShardAuthorityException(
|
||||
shard,
|
||||
$"Shard '{shard.ShardId}' log entry {entry.Sequence} targets a different shard or epoch.",
|
||||
"stale_epoch");
|
||||
}
|
||||
|
||||
var key = new CultRecordKey(message.Document.RecordKey);
|
||||
var descriptor = _cache.Registry.GetRequiredBySchemaId(message.Document.SchemaId);
|
||||
var previous = _cache.Get(key);
|
||||
var document = await _documents.ApplyRawDocumentPutMessageAsync(_cache, message).ConfigureAwait(false);
|
||||
var kind = ChangeKindFromWire(entry.ChangeKind);
|
||||
if (kind == CultNetDatabaseChangeKind.Removed)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Shard '{shard.ShardId}' log entry {entry.Sequence} has a removed kind with a put payload.");
|
||||
}
|
||||
|
||||
RecordMutationLogEntry(new CultNetShardMutationLogEntry(
|
||||
shard.ShardId,
|
||||
shard.Epoch,
|
||||
entry.Sequence,
|
||||
entry.CommittedAt,
|
||||
kind,
|
||||
descriptor.SchemaId,
|
||||
key,
|
||||
document,
|
||||
previous));
|
||||
PublishUntyped(
|
||||
descriptor.DocumentType,
|
||||
kind,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document,
|
||||
previous);
|
||||
}
|
||||
|
||||
private void ApplyCommittedDelete(
|
||||
CultNetShardDescriptor shard,
|
||||
CultNetShardLogEntryMessage entry)
|
||||
{
|
||||
var message = entry.Delete!;
|
||||
if (!string.Equals(message.ShardId, shard.ShardId, StringComparison.Ordinal) ||
|
||||
message.ShardEpoch != shard.Epoch)
|
||||
{
|
||||
throw new CultNetShardAuthorityException(
|
||||
shard,
|
||||
$"Shard '{shard.ShardId}' log entry {entry.Sequence} targets a different shard or epoch.",
|
||||
"stale_epoch");
|
||||
}
|
||||
|
||||
var key = new CultRecordKey(message.RecordKey);
|
||||
var descriptor = _cache.Registry.GetRequiredBySchemaId(message.SchemaId);
|
||||
var previous = _cache.Get(key);
|
||||
if (previous != null)
|
||||
{
|
||||
var removeMethod = typeof(CultCache).GetMethod(nameof(CultCache.Remove))!
|
||||
.MakeGenericMethod(descriptor.DocumentType);
|
||||
var handleType = typeof(CultRecordHandle<>).MakeGenericType(descriptor.DocumentType);
|
||||
var handle = Activator.CreateInstance(handleType, new object[] { key });
|
||||
removeMethod.Invoke(_cache, new[] { handle });
|
||||
}
|
||||
|
||||
RecordMutationLogEntry(new CultNetShardMutationLogEntry(
|
||||
shard.ShardId,
|
||||
shard.Epoch,
|
||||
entry.Sequence,
|
||||
entry.CommittedAt,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
descriptor.SchemaId,
|
||||
key,
|
||||
document: null,
|
||||
previousDocument: previous));
|
||||
PublishUntyped(
|
||||
descriptor.DocumentType,
|
||||
CultNetDatabaseChangeKind.Removed,
|
||||
key,
|
||||
descriptor.SchemaId,
|
||||
shard,
|
||||
document: null,
|
||||
previousDocument: previous);
|
||||
}
|
||||
|
||||
private static CultNetDatabaseChangeKind ChangeKindFromWire(string changeKind)
|
||||
{
|
||||
return changeKind switch
|
||||
{
|
||||
"added" => CultNetDatabaseChangeKind.Added,
|
||||
"updated" => CultNetDatabaseChangeKind.Updated,
|
||||
"removed" => CultNetDatabaseChangeKind.Removed,
|
||||
_ => throw new InvalidOperationException($"Unsupported shard log change kind '{changeKind}'.")
|
||||
};
|
||||
}
|
||||
|
||||
private void PublishUntyped(
|
||||
|
|
|
|||
|
|
@ -138,7 +138,9 @@ write rejection. Non-primary write forwarding is available behind an injectable
|
|||
schema-v0 `cultnet://host:port` endpoint dialer. It also records accepted
|
||||
mutations in per-shard ordered logs and exposes those logs over
|
||||
`cultnet.shard_log_request.v0` / `cultnet.shard_log_response.v0` for replica
|
||||
catch-up.
|
||||
catch-up. Replicas apply those committed entries through
|
||||
`CultNetDatabase.ApplyShardLogResponseAsync`, which checks shard epoch, rejects
|
||||
sequence gaps, and treats replayed entries as already applied.
|
||||
|
||||
The first coherent shard policy is primary ownership. Each shard has one
|
||||
authoritative writer at a time. Clients may connect to any node; a non-owner
|
||||
|
|
|
|||
|
|
@ -849,6 +849,129 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(response.Entries[0].Delete!.ShardEpoch, Is.EqualTo(6));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultNetDatabase_Applies_ShardLogResponse_ToReplica()
|
||||
{
|
||||
var sourceCache = new CultCache();
|
||||
var targetCache = new CultCache();
|
||||
var sourceRegistry = new CultNetDocumentRegistry(sourceCache.Registry)
|
||||
.Register(CultNetDocumentBinding.ForDocument<PlayerData>(
|
||||
sourceCache.Registry,
|
||||
payloadSerializer: SerializePlayerDataPayload,
|
||||
payloadDeserializer: DeserializePlayerDataPayload));
|
||||
var targetRegistry = new CultNetDocumentRegistry(targetCache.Registry)
|
||||
.Register(CultNetDocumentBinding.ForDocument<PlayerData>(
|
||||
targetCache.Registry,
|
||||
payloadSerializer: SerializePlayerDataPayload,
|
||||
payloadDeserializer: DeserializePlayerDataPayload));
|
||||
var schemaId = sourceCache.Registry.GetRequired<PlayerData>().SchemaId;
|
||||
var sourceDatabase = new CultNetDatabase(sourceCache, new CultNetDatabaseOptions
|
||||
{
|
||||
DocumentRegistry = sourceRegistry,
|
||||
Shards =
|
||||
[
|
||||
new CultNetShardDescriptor(
|
||||
"players-replica",
|
||||
"runtime-a",
|
||||
epoch: 10,
|
||||
isPrimary: true,
|
||||
schemaIds: [schemaId],
|
||||
keyPrefix: "player:")
|
||||
]
|
||||
});
|
||||
var targetDatabase = new CultNetDatabase(targetCache, new CultNetDatabaseOptions
|
||||
{
|
||||
DocumentRegistry = targetRegistry,
|
||||
Shards =
|
||||
[
|
||||
new CultNetShardDescriptor(
|
||||
"players-replica",
|
||||
"runtime-a",
|
||||
epoch: 10,
|
||||
isPrimary: false,
|
||||
schemaIds: [schemaId],
|
||||
keyPrefix: "player:")
|
||||
]
|
||||
});
|
||||
using var server = new Server(sourceCache, DevelopmentServerSecurity);
|
||||
using var databaseServer = new CultNetDatabaseServer(server, sourceDatabase);
|
||||
var key = new CultRecordKey("player:replica");
|
||||
var player = new PlayerData
|
||||
{
|
||||
PlayerId = Guid.NewGuid(),
|
||||
Email = "replica@example.test",
|
||||
PasswordHash = "hash",
|
||||
Username = "Replica"
|
||||
};
|
||||
|
||||
await sourceDatabase.PutAsync(key, player);
|
||||
var response = databaseServer.CreateShardLogResponse(new CultNetShardLogRequestMessage
|
||||
{
|
||||
ShardId = "players-replica",
|
||||
ShardEpoch = 10
|
||||
});
|
||||
|
||||
var sequence = await targetDatabase.ApplyShardLogResponseAsync(response);
|
||||
var replicated = targetCache.Get<PlayerData>(key);
|
||||
var replayedSequence = await targetDatabase.ApplyShardLogResponseAsync(response);
|
||||
|
||||
Assert.That(sequence, Is.EqualTo(1));
|
||||
Assert.That(replayedSequence, Is.EqualTo(1));
|
||||
Assert.That(targetDatabase.GetAppliedShardSequence("players-replica"), Is.EqualTo(1));
|
||||
Assert.That(replicated, Is.Not.Null);
|
||||
Assert.That(replicated!.Username, Is.EqualTo("Replica"));
|
||||
Assert.That(targetDatabase.GetMutationLog("players-replica"), Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CultNetDatabase_Rejects_ShardLogGap()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var registry = new CultNetDocumentRegistry(cache.Registry)
|
||||
.Register(CultNetDocumentBinding.ForDocument<PlayerData>(
|
||||
cache.Registry,
|
||||
payloadSerializer: SerializePlayerDataPayload,
|
||||
payloadDeserializer: DeserializePlayerDataPayload));
|
||||
var schemaId = cache.Registry.GetRequired<PlayerData>().SchemaId;
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions
|
||||
{
|
||||
DocumentRegistry = registry,
|
||||
Shards =
|
||||
[
|
||||
new CultNetShardDescriptor(
|
||||
"players-gap",
|
||||
"runtime-a",
|
||||
epoch: 1,
|
||||
isPrimary: false,
|
||||
schemaIds: [schemaId],
|
||||
keyPrefix: "player:")
|
||||
]
|
||||
});
|
||||
|
||||
Assert.That(
|
||||
async () => await database.ApplyShardLogResponseAsync(new CultNetShardLogResponseMessage
|
||||
{
|
||||
ShardId = "players-gap",
|
||||
ShardEpoch = 1,
|
||||
Entries =
|
||||
[
|
||||
new CultNetShardLogEntryMessage
|
||||
{
|
||||
Sequence = 2,
|
||||
ChangeKind = "removed",
|
||||
Delete = new CultNetDocumentDeleteMessage
|
||||
{
|
||||
SchemaId = schemaId,
|
||||
RecordKey = "player:gap",
|
||||
ShardId = "players-gap",
|
||||
ShardEpoch = 1
|
||||
}
|
||||
}
|
||||
]
|
||||
}),
|
||||
Throws.TypeOf<InvalidOperationException>().With.Message.Contains("log has a gap"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CultNetDatabaseServer_Creates_Filtered_SubscriptionChange()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue