Add CultNet shard catalog routing
This commit is contained in:
parent
5c4195677d
commit
4af500a87d
8 changed files with 440 additions and 20 deletions
|
|
@ -152,9 +152,9 @@ The coherent path is:
|
|||
details.
|
||||
- Conflict policy must be declared before conflicting writes are accepted.
|
||||
|
||||
## Next Cut
|
||||
## Current Cut
|
||||
|
||||
Build shard catalog exchange:
|
||||
Shard catalog exchange now exists:
|
||||
|
||||
- `cultnet.shard_catalog_request.v0`
|
||||
- `cultnet.shard_catalog_response.v0`
|
||||
|
|
@ -162,5 +162,15 @@ Build shard catalog exchange:
|
|||
- stale epoch rejection on writes
|
||||
- routing error that tells clients where the primary lives when known
|
||||
|
||||
That is the next foundation needed before forwarding, membership, Raft-style
|
||||
replication, or CRDT policy work can be honest.
|
||||
## Next Cut
|
||||
|
||||
Build write forwarding:
|
||||
|
||||
- non-primary nodes forward raw put/delete messages to primary endpoints when
|
||||
policy allows
|
||||
- forwarded writes preserve shard id and epoch
|
||||
- stale epochs still fail
|
||||
- clients can opt into direct retry using routing hints
|
||||
|
||||
That is the next foundation needed before membership, Raft-style replication,
|
||||
or CRDT policy work can be honest.
|
||||
|
|
|
|||
|
|
@ -39,10 +39,14 @@ Implemented:
|
|||
- `CultNetHost.Database` and `CultNetHost.DatabaseServer`
|
||||
- subscription request/cancel/change messages
|
||||
- server-side live change fanout for schema/key-filtered subscriptions
|
||||
- shard catalog request/response messages
|
||||
- shard descriptors with owner runtime id, epoch, schema filters, key prefix,
|
||||
primary endpoints, replica endpoints, read replica endpoints, and region
|
||||
- epoch-aware raw put/delete messages
|
||||
- routing hints on shard authority errors
|
||||
|
||||
Not implemented yet:
|
||||
|
||||
- shard catalog exchange
|
||||
- membership/failure detection
|
||||
- leader election or automatic shard failover
|
||||
- replicated log
|
||||
|
|
@ -62,13 +66,14 @@ Not implemented yet:
|
|||
|
||||
## Next Coherent Slice
|
||||
|
||||
Add shard catalog exchange:
|
||||
Add write forwarding:
|
||||
|
||||
- advertise shard ids, schema filters, key ranges/prefixes, owner runtime ids,
|
||||
and epochs
|
||||
- let clients ask any node where a write belongs
|
||||
- reject stale-epoch writes explicitly
|
||||
- prepare forwarding without making forwarding mandatory
|
||||
- non-primary nodes can forward raw put/delete messages to the advertised
|
||||
primary endpoint when policy allows it
|
||||
- forwarded writes must preserve the original shard id and epoch
|
||||
- stale-epoch writes still fail instead of being "helpfully" retried against
|
||||
unknown authority
|
||||
- clients that opt out of forwarding receive routing hints and retry directly
|
||||
|
||||
That gives the subscription surface a real routing model before membership,
|
||||
leader election, or replicated logs enter the room and start charging rent.
|
||||
Forwarding is the next useful layer now that shard catalogs exist. Membership,
|
||||
leader election, and replicated logs should wait until routing is boring.
|
||||
|
|
|
|||
|
|
@ -48,7 +48,11 @@ namespace GameCult.Networking
|
|||
long epoch,
|
||||
bool isPrimary,
|
||||
IEnumerable<string>? schemaIds = null,
|
||||
string? keyPrefix = null)
|
||||
string? keyPrefix = null,
|
||||
IEnumerable<string>? primaryEndpoints = null,
|
||||
IEnumerable<string>? replicaEndpoints = null,
|
||||
IEnumerable<string>? readReplicaEndpoints = null,
|
||||
string? region = null)
|
||||
{
|
||||
ShardId = RequireNonEmpty(shardId, nameof(shardId));
|
||||
OwnerRuntimeId = RequireNonEmpty(ownerRuntimeId, nameof(ownerRuntimeId));
|
||||
|
|
@ -57,6 +61,10 @@ namespace GameCult.Networking
|
|||
SchemaIds = schemaIds?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<string>();
|
||||
KeyPrefix = keyPrefix;
|
||||
PrimaryEndpoints = CleanEndpoints(primaryEndpoints);
|
||||
ReplicaEndpoints = CleanEndpoints(replicaEndpoints);
|
||||
ReadReplicaEndpoints = CleanEndpoints(readReplicaEndpoints);
|
||||
Region = region;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -83,6 +91,22 @@ namespace GameCult.Networking
|
|||
/// Gets the optional record-key prefix governed by this shard.
|
||||
/// </summary>
|
||||
public string? KeyPrefix { get; }
|
||||
/// <summary>
|
||||
/// Gets endpoints that can accept authoritative writes for this shard.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> PrimaryEndpoints { get; }
|
||||
/// <summary>
|
||||
/// Gets endpoints that replicate authoritative shard mutations.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> ReplicaEndpoints { get; }
|
||||
/// <summary>
|
||||
/// Gets endpoints intended for low-latency read and subscription traffic.
|
||||
/// </summary>
|
||||
public IReadOnlyList<string> ReadReplicaEndpoints { get; }
|
||||
/// <summary>
|
||||
/// Gets an optional locality label for this shard owner.
|
||||
/// </summary>
|
||||
public string? Region { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Creates a primary shard that accepts every schema and key.
|
||||
|
|
@ -122,6 +146,12 @@ namespace GameCult.Networking
|
|||
|
||||
return value;
|
||||
}
|
||||
|
||||
private static string[] CleanEndpoints(IEnumerable<string>? endpoints)
|
||||
{
|
||||
return endpoints?.Where(value => !string.IsNullOrWhiteSpace(value)).Distinct(StringComparer.Ordinal).ToArray()
|
||||
?? Array.Empty<string>();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -257,6 +287,35 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public IReadOnlyList<CultNetShardDescriptor> Shards => _shards;
|
||||
|
||||
/// <summary>
|
||||
/// Creates a shard catalog response for optional schema/key filters.
|
||||
/// </summary>
|
||||
public CultNetShardCatalogResponseMessage CreateShardCatalogResponse(CultNetShardCatalogRequestMessage request)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
if (request == null) throw new ArgumentNullException(nameof(request));
|
||||
|
||||
var schemaIds = request.SchemaIds == null || request.SchemaIds.Length == 0
|
||||
? null
|
||||
: request.SchemaIds;
|
||||
var recordKeys = request.RecordKeys == null || request.RecordKeys.Length == 0
|
||||
? null
|
||||
: request.RecordKeys.Select(key => new CultRecordKey(key)).ToArray();
|
||||
|
||||
var descriptors = _shards
|
||||
.Where(shard => MatchesCatalogFilter(shard, schemaIds, recordKeys))
|
||||
.Select(ToMessage)
|
||||
.ToArray();
|
||||
|
||||
return new CultNetShardCatalogResponseMessage
|
||||
{
|
||||
MessageId = string.IsNullOrWhiteSpace(request.MessageId)
|
||||
? Guid.NewGuid().ToString("N")
|
||||
: request.MessageId,
|
||||
Shards = descriptors
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a document by key.
|
||||
/// </summary>
|
||||
|
|
@ -330,7 +389,7 @@ namespace GameCult.Networking
|
|||
|
||||
var key = new CultRecordKey(message.Document.RecordKey);
|
||||
var shard = ResolveShard(message.Document.SchemaId, key);
|
||||
EnsurePrimary(shard, message.Document.SchemaId, key);
|
||||
EnsurePrimary(shard, message.Document.SchemaId, key, message.ShardEpoch);
|
||||
var descriptor = _cache.Registry.GetRequiredBySchemaId(message.Document.SchemaId);
|
||||
var previous = _cache.Get(key);
|
||||
var document = await _documents.ApplyRawDocumentPutMessageAsync(_cache, message).ConfigureAwait(false);
|
||||
|
|
@ -355,7 +414,7 @@ namespace GameCult.Networking
|
|||
|
||||
var key = new CultRecordKey(message.RecordKey);
|
||||
var shard = ResolveShard(message.SchemaId, key);
|
||||
EnsurePrimary(shard, message.SchemaId, key);
|
||||
EnsurePrimary(shard, message.SchemaId, key, message.ShardEpoch);
|
||||
var descriptor = _cache.Registry.GetRequiredBySchemaId(message.SchemaId);
|
||||
var previous = _cache.Get(key);
|
||||
if (previous == null)
|
||||
|
|
@ -537,8 +596,15 @@ namespace GameCult.Networking
|
|||
return _shards.FirstOrDefault(shard => shard.Matches(schemaId, key)) ?? _shards[0];
|
||||
}
|
||||
|
||||
private static void EnsurePrimary(CultNetShardDescriptor shard, string schemaId, CultRecordKey key)
|
||||
private static void EnsurePrimary(CultNetShardDescriptor shard, string schemaId, CultRecordKey key, long? expectedEpoch = null)
|
||||
{
|
||||
if (expectedEpoch.HasValue && expectedEpoch.Value != shard.Epoch)
|
||||
{
|
||||
throw new CultNetShardAuthorityException(
|
||||
shard,
|
||||
$"Shard '{shard.ShardId}' is at epoch {shard.Epoch}, not requested epoch {expectedEpoch.Value}.");
|
||||
}
|
||||
|
||||
if (shard.IsPrimary)
|
||||
{
|
||||
return;
|
||||
|
|
@ -549,6 +615,39 @@ namespace GameCult.Networking
|
|||
$"Shard '{shard.ShardId}' owned by '{shard.OwnerRuntimeId}' does not accept local writes for schema '{schemaId}' key '{key.Value}'.");
|
||||
}
|
||||
|
||||
private static bool MatchesCatalogFilter(
|
||||
CultNetShardDescriptor shard,
|
||||
IReadOnlyList<string>? schemaIds,
|
||||
IReadOnlyList<CultRecordKey>? recordKeys)
|
||||
{
|
||||
var schemaMatches = schemaIds == null ||
|
||||
schemaIds.Count == 0 ||
|
||||
shard.SchemaIds.Count == 0 ||
|
||||
schemaIds.Any(schemaId => shard.SchemaIds.Contains(schemaId, StringComparer.Ordinal));
|
||||
var keyMatches = recordKeys == null ||
|
||||
recordKeys.Count == 0 ||
|
||||
recordKeys.Any(key => string.IsNullOrEmpty(shard.KeyPrefix) ||
|
||||
key.Value.StartsWith(shard.KeyPrefix!, StringComparison.Ordinal));
|
||||
return schemaMatches && keyMatches;
|
||||
}
|
||||
|
||||
internal static CultNetShardDescriptorMessage ToMessage(CultNetShardDescriptor shard)
|
||||
{
|
||||
return new CultNetShardDescriptorMessage
|
||||
{
|
||||
ShardId = shard.ShardId,
|
||||
OwnerRuntimeId = shard.OwnerRuntimeId,
|
||||
Epoch = shard.Epoch,
|
||||
IsPrimary = shard.IsPrimary,
|
||||
SchemaIds = shard.SchemaIds.ToArray(),
|
||||
KeyPrefix = shard.KeyPrefix,
|
||||
PrimaryEndpoints = shard.PrimaryEndpoints.ToArray(),
|
||||
ReplicaEndpoints = shard.ReplicaEndpoints.ToArray(),
|
||||
ReadReplicaEndpoints = shard.ReadReplicaEndpoints.ToArray(),
|
||||
Region = shard.Region
|
||||
};
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
if (_disposed)
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ namespace GameCult.Networking
|
|||
private readonly Func<CultNetSnapshotRequestMessage, NetPeer, Task> _snapshotHandler;
|
||||
private readonly Func<CultNetDocumentPutRawMessage, NetPeer, Task> _putHandler;
|
||||
private readonly Func<CultNetDocumentDeleteMessage, NetPeer, Task> _deleteHandler;
|
||||
private readonly Func<CultNetShardCatalogRequestMessage, NetPeer, Task> _shardCatalogHandler;
|
||||
private readonly Func<CultNetDatabaseSubscribeMessage, NetPeer, Task> _subscribeHandler;
|
||||
private readonly Func<CultNetDatabaseUnsubscribeMessage, NetPeer, Task> _unsubscribeHandler;
|
||||
private readonly ConcurrentDictionary<string, IDisposable> _subscriptions = new(StringComparer.Ordinal);
|
||||
|
|
@ -34,12 +35,14 @@ namespace GameCult.Networking
|
|||
_snapshotHandler = HandleSnapshotRequestAsync;
|
||||
_putHandler = HandlePutAsync;
|
||||
_deleteHandler = HandleDeleteAsync;
|
||||
_shardCatalogHandler = HandleShardCatalogRequestAsync;
|
||||
_subscribeHandler = HandleSubscribeAsync;
|
||||
_unsubscribeHandler = HandleUnsubscribeAsync;
|
||||
|
||||
_server.OnCultNet(_snapshotHandler);
|
||||
_server.OnCultNet(_putHandler);
|
||||
_server.OnCultNet(_deleteHandler);
|
||||
_server.OnCultNet(_shardCatalogHandler);
|
||||
_server.OnCultNet(_subscribeHandler);
|
||||
_server.OnCultNet(_unsubscribeHandler);
|
||||
}
|
||||
|
|
@ -77,6 +80,14 @@ namespace GameCult.Networking
|
|||
request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a shard catalog response from the database shard map.
|
||||
/// </summary>
|
||||
public CultNetShardCatalogResponseMessage CreateShardCatalogResponse(CultNetShardCatalogRequestMessage request)
|
||||
{
|
||||
return _database.CreateShardCatalogResponse(request);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detaches handlers from the server.
|
||||
/// </summary>
|
||||
|
|
@ -91,6 +102,7 @@ namespace GameCult.Networking
|
|||
_server.RemoveCultNetMessageListener<CultNetSnapshotRequestMessage>(_snapshotHandler);
|
||||
_server.RemoveCultNetMessageListener<CultNetDocumentPutRawMessage>(_putHandler);
|
||||
_server.RemoveCultNetMessageListener<CultNetDocumentDeleteMessage>(_deleteHandler);
|
||||
_server.RemoveCultNetMessageListener<CultNetShardCatalogRequestMessage>(_shardCatalogHandler);
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseSubscribeMessage>(_subscribeHandler);
|
||||
_server.RemoveCultNetMessageListener<CultNetDatabaseUnsubscribeMessage>(_unsubscribeHandler);
|
||||
foreach (var subscription in _subscriptions.Values)
|
||||
|
|
@ -107,12 +119,22 @@ namespace GameCult.Networking
|
|||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task HandleShardCatalogRequestAsync(CultNetShardCatalogRequestMessage request, NetPeer peer)
|
||||
{
|
||||
peer.SendCultNet(CreateShardCatalogResponse(request));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task HandlePutAsync(CultNetDocumentPutRawMessage message, NetPeer peer)
|
||||
{
|
||||
try
|
||||
{
|
||||
await ApplyPutAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
catch (CultNetShardAuthorityException ex)
|
||||
{
|
||||
peer.SendCultNet(CreateRoutingError(ex));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
peer.SendCultNet(new CultNetErrorMessage { Error = ex.Message });
|
||||
|
|
@ -125,6 +147,10 @@ namespace GameCult.Networking
|
|||
{
|
||||
await ApplyDeleteAsync(message).ConfigureAwait(false);
|
||||
}
|
||||
catch (CultNetShardAuthorityException ex)
|
||||
{
|
||||
peer.SendCultNet(CreateRoutingError(ex));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
peer.SendCultNet(new CultNetErrorMessage { Error = ex.Message });
|
||||
|
|
@ -260,5 +286,18 @@ namespace GameCult.Networking
|
|||
{
|
||||
return $"{peer.Id}:{subscriptionId}";
|
||||
}
|
||||
|
||||
private static CultNetErrorMessage CreateRoutingError(CultNetShardAuthorityException exception)
|
||||
{
|
||||
return new CultNetErrorMessage
|
||||
{
|
||||
Error = exception.Message,
|
||||
RoutingHint = new CultNetShardRoutingHint
|
||||
{
|
||||
Reason = exception.Shard.IsPrimary ? "stale_epoch" : "not_primary",
|
||||
Shard = CultNetDatabase.ToMessage(exception.Shard)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,6 +62,8 @@ namespace GameCult.Networking
|
|||
CultNetSchemaVersions.DatabaseSubscribe => Deserialize<CultNetDatabaseSubscribeMessage>(payload),
|
||||
CultNetSchemaVersions.DatabaseUnsubscribe => Deserialize<CultNetDatabaseUnsubscribeMessage>(payload),
|
||||
CultNetSchemaVersions.DatabaseChangeRaw => Deserialize<CultNetDatabaseChangeRawMessage>(payload),
|
||||
CultNetSchemaVersions.ShardCatalogRequest => Deserialize<CultNetShardCatalogRequestMessage>(payload),
|
||||
CultNetSchemaVersions.ShardCatalogResponse => Deserialize<CultNetShardCatalogResponseMessage>(payload),
|
||||
CultNetSchemaVersions.SchemaCatalogRequest => Deserialize<CultNetSchemaCatalogRequestMessage>(payload),
|
||||
CultNetSchemaVersions.SchemaCatalogResponse => Deserialize<CultNetSchemaCatalogResponseMessage>(payload),
|
||||
_ => throw new MessagePackSerializationException(
|
||||
|
|
|
|||
|
|
@ -91,6 +91,14 @@ namespace GameCult.Networking
|
|||
/// database subscription change contract identifier.
|
||||
/// </summary>
|
||||
public const string DatabaseChangeRaw = "cultnet.database_change_raw.v0";
|
||||
/// <summary>
|
||||
/// shard catalog request contract identifier.
|
||||
/// </summary>
|
||||
public const string ShardCatalogRequest = "cultnet.shard_catalog_request.v0";
|
||||
/// <summary>
|
||||
/// shard catalog response contract identifier.
|
||||
/// </summary>
|
||||
public const string ShardCatalogResponse = "cultnet.shard_catalog_response.v0";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -321,6 +329,26 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the error.
|
||||
/// </summary>
|
||||
[Key("error")] public string Error { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Gets or sets optional shard routing details for authority failures.
|
||||
/// </summary>
|
||||
[Key("routingHint")] public CultNetShardRoutingHint? RoutingHint { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes where a shard write should be routed.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultNetShardRoutingHint
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the shard descriptor.
|
||||
/// </summary>
|
||||
[Key("shard")] public CultNetShardDescriptorMessage? Shard { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets a machine-readable routing reason.
|
||||
/// </summary>
|
||||
[Key("reason")] public string Reason { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -421,6 +449,14 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the record key.
|
||||
/// </summary>
|
||||
[Key("recordKey")] public string RecordKey { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Gets or sets the shard id the sender targeted.
|
||||
/// </summary>
|
||||
[Key("shardId")] public string? ShardId { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the shard epoch the sender targeted.
|
||||
/// </summary>
|
||||
[Key("shardEpoch")] public long? ShardEpoch { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -441,6 +477,14 @@ namespace GameCult.Networking
|
|||
/// Gets or sets the document.
|
||||
/// </summary>
|
||||
[Key("document")] public CultNetRawDocumentRecord Document { get; set; } = new CultNetRawDocumentRecord();
|
||||
/// <summary>
|
||||
/// Gets or sets the shard id the sender targeted.
|
||||
/// </summary>
|
||||
[Key("shardId")] public string? ShardId { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets the shard epoch the sender targeted.
|
||||
/// </summary>
|
||||
[Key("shardEpoch")] public long? ShardEpoch { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -575,6 +619,98 @@ namespace GameCult.Networking
|
|||
[Key("schemaId")] public string? SchemaId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes one shard advertised by a CultNet database node.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultNetShardDescriptorMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the shard id.
|
||||
/// </summary>
|
||||
[Key("shardId")] public string ShardId { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Gets or sets the owner runtime id.
|
||||
/// </summary>
|
||||
[Key("ownerRuntimeId")] public string OwnerRuntimeId { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Gets or sets the shard authority epoch.
|
||||
/// </summary>
|
||||
[Key("epoch")] public long Epoch { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets whether the responding node is primary for this shard.
|
||||
/// </summary>
|
||||
[Key("isPrimary")] public bool IsPrimary { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets schema ids governed by this shard. Empty means all schemas.
|
||||
/// </summary>
|
||||
[Key("schemaIds")] public string[] SchemaIds { get; set; } = Array.Empty<string>();
|
||||
/// <summary>
|
||||
/// Gets or sets the record-key prefix governed by this shard.
|
||||
/// </summary>
|
||||
[Key("keyPrefix")] public string? KeyPrefix { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets endpoints that accept authoritative writes.
|
||||
/// </summary>
|
||||
[Key("primaryEndpoints")] public string[] PrimaryEndpoints { get; set; } = Array.Empty<string>();
|
||||
/// <summary>
|
||||
/// Gets or sets authoritative replica endpoints.
|
||||
/// </summary>
|
||||
[Key("replicaEndpoints")] public string[] ReplicaEndpoints { get; set; } = Array.Empty<string>();
|
||||
/// <summary>
|
||||
/// Gets or sets low-latency read replica endpoints.
|
||||
/// </summary>
|
||||
[Key("readReplicaEndpoints")] public string[] ReadReplicaEndpoints { get; set; } = Array.Empty<string>();
|
||||
/// <summary>
|
||||
/// Gets or sets an optional locality label.
|
||||
/// </summary>
|
||||
[Key("region")] public string? Region { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests shard ownership and routing metadata.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultNetShardCatalogRequestMessage : ICultNetSchemaMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the schema version.
|
||||
/// </summary>
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ShardCatalogRequest;
|
||||
/// <summary>
|
||||
/// Gets or sets the request id.
|
||||
/// </summary>
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Gets or sets optional schema filters.
|
||||
/// </summary>
|
||||
[Key("schemaIds")] public string[]? SchemaIds { get; set; }
|
||||
/// <summary>
|
||||
/// Gets or sets optional record-key filters.
|
||||
/// </summary>
|
||||
[Key("recordKeys")] public string[]? RecordKeys { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns shard ownership and routing metadata.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultNetShardCatalogResponseMessage : ICultNetSchemaMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the schema version.
|
||||
/// </summary>
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ShardCatalogResponse;
|
||||
/// <summary>
|
||||
/// Gets or sets the request id.
|
||||
/// </summary>
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// Gets or sets shard descriptors.
|
||||
/// </summary>
|
||||
[Key("shards")] public CultNetShardDescriptorMessage[] Shards { get; set; } = Array.Empty<CultNetShardDescriptorMessage>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes one schema exposed through the CultNet schema catalog.
|
||||
/// </summary>
|
||||
|
|
|
|||
|
|
@ -131,9 +131,9 @@ CultNet becomes the distribution model:
|
|||
|
||||
The current first slice exposes this as `CultNetDatabase` and wires hosted
|
||||
servers through `CultNetDatabaseServer`. It handles primary-shard writes, typed
|
||||
R3 watch streams, raw document puts/deletes, raw snapshot responses, and
|
||||
schema/key-filtered live subscriptions. Shard catalog exchange is the next
|
||||
missing organ.
|
||||
R3 watch streams, raw document puts/deletes, raw snapshot responses,
|
||||
schema/key-filtered live subscriptions, shard catalog exchange, and stale-epoch
|
||||
write rejection. Write forwarding is the next missing organ.
|
||||
|
||||
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
|
||||
|
|
|
|||
|
|
@ -241,6 +241,41 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(roundTrip.Document!.RecordKey, Is.EqualTo("record-1"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CultNetSchemaMessageSerialization_RoundTrips_ShardCatalogResponse()
|
||||
{
|
||||
var message = new CultNetShardCatalogResponseMessage
|
||||
{
|
||||
MessageId = "shards-1",
|
||||
Shards =
|
||||
[
|
||||
new CultNetShardDescriptorMessage
|
||||
{
|
||||
ShardId = "players-eu",
|
||||
OwnerRuntimeId = "runtime-a",
|
||||
Epoch = 12,
|
||||
IsPrimary = true,
|
||||
SchemaIds = ["schema-player"],
|
||||
KeyPrefix = "player:",
|
||||
PrimaryEndpoints = ["cultnet://runtime-a:3075"],
|
||||
ReplicaEndpoints = ["cultnet://runtime-b:3075"],
|
||||
ReadReplicaEndpoints = ["cultnet://edge-1:3075"],
|
||||
Region = "eu-west"
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
var payload = CultNetSchemaMessageSerialization.Serialize(message);
|
||||
var roundTrip = (CultNetShardCatalogResponseMessage)CultNetSchemaMessageSerialization.Deserialize(payload);
|
||||
|
||||
Assert.That(roundTrip.MessageId, Is.EqualTo("shards-1"));
|
||||
Assert.That(roundTrip.Shards, Has.Length.EqualTo(1));
|
||||
Assert.That(roundTrip.Shards[0].ShardId, Is.EqualTo("players-eu"));
|
||||
Assert.That(roundTrip.Shards[0].Epoch, Is.EqualTo(12));
|
||||
Assert.That(roundTrip.Shards[0].PrimaryEndpoints, Is.EqualTo(["cultnet://runtime-a:3075"]));
|
||||
Assert.That(roundTrip.Shards[0].Region, Is.EqualTo("eu-west"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultNetDocumentRegistry_RawSnapshotReplication_PreservesPayloadBytes()
|
||||
{
|
||||
|
|
@ -342,6 +377,53 @@ namespace GameCult.Networking.Tests
|
|||
.EqualTo("remote-players"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultNetDatabase_Rejects_RawPut_With_StaleShardEpoch()
|
||||
{
|
||||
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",
|
||||
"runtime-a",
|
||||
epoch: 7,
|
||||
isPrimary: true,
|
||||
schemaIds: [schemaId],
|
||||
keyPrefix: "player:",
|
||||
primaryEndpoints: ["cultnet://runtime-a:3075"])
|
||||
]
|
||||
});
|
||||
var key = new CultRecordKey("player:stale");
|
||||
var message = registry.CreateRawDocumentPutMessage(
|
||||
"put-stale",
|
||||
new CultRecordHandle<PlayerData>(key),
|
||||
new PlayerData
|
||||
{
|
||||
PlayerId = Guid.NewGuid(),
|
||||
Email = "stale@example.test",
|
||||
PasswordHash = "hash",
|
||||
Username = "Stale"
|
||||
});
|
||||
message.ShardId = "players";
|
||||
message.ShardEpoch = 6;
|
||||
|
||||
Assert.That(
|
||||
async () => await database.ApplyPutAsync(message),
|
||||
Throws.TypeOf<CultNetShardAuthorityException>()
|
||||
.With.Property(nameof(CultNetShardAuthorityException.Shard))
|
||||
.Property(nameof(CultNetShardDescriptor.Epoch))
|
||||
.EqualTo(7));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultNetDatabase_ApplyRawPut_Publishes_DomainChange()
|
||||
{
|
||||
|
|
@ -416,6 +498,53 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(response.Documents[0].Payload, Is.EqualTo(SerializePlayerDataPayload(player)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CultNetDatabaseServer_Creates_Filtered_ShardCatalogResponse()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var schemaId = cache.Registry.GetRequired<PlayerData>().SchemaId;
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions
|
||||
{
|
||||
Shards =
|
||||
[
|
||||
new CultNetShardDescriptor(
|
||||
"players",
|
||||
"runtime-a",
|
||||
epoch: 3,
|
||||
isPrimary: true,
|
||||
schemaIds: [schemaId],
|
||||
keyPrefix: "player:",
|
||||
primaryEndpoints: ["cultnet://runtime-a:3075"],
|
||||
replicaEndpoints: ["cultnet://runtime-b:3075"],
|
||||
readReplicaEndpoints: ["cultnet://edge-a:3075"],
|
||||
region: "eu-west"),
|
||||
new CultNetShardDescriptor(
|
||||
"world",
|
||||
"runtime-c",
|
||||
epoch: 1,
|
||||
isPrimary: false,
|
||||
schemaIds: ["schema-world"],
|
||||
keyPrefix: "world:")
|
||||
]
|
||||
});
|
||||
using var server = new Server(cache, DevelopmentServerSecurity);
|
||||
using var databaseServer = new CultNetDatabaseServer(server, database);
|
||||
|
||||
var response = databaseServer.CreateShardCatalogResponse(new CultNetShardCatalogRequestMessage
|
||||
{
|
||||
MessageId = "catalog-players",
|
||||
SchemaIds = [schemaId],
|
||||
RecordKeys = ["player:one"]
|
||||
});
|
||||
|
||||
Assert.That(response.MessageId, Is.EqualTo("catalog-players"));
|
||||
Assert.That(response.Shards, Has.Length.EqualTo(1));
|
||||
Assert.That(response.Shards[0].ShardId, Is.EqualTo("players"));
|
||||
Assert.That(response.Shards[0].Epoch, Is.EqualTo(3));
|
||||
Assert.That(response.Shards[0].PrimaryEndpoints, Is.EqualTo(["cultnet://runtime-a:3075"]));
|
||||
Assert.That(response.Shards[0].ReadReplicaEndpoints, Is.EqualTo(["cultnet://edge-a:3075"]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CultNetDatabaseServer_Creates_Filtered_SubscriptionChange()
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue