diff --git a/src/GameCult.Networking/CultNetDatabase.cs b/src/GameCult.Networking/CultNetDatabase.cs
index 4ef5820b..083d309f 100644
--- a/src/GameCult.Networking/CultNetDatabase.cs
+++ b/src/GameCult.Networking/CultNetDatabase.cs
@@ -501,7 +501,8 @@ namespace GameCult.Networking
}
///
- /// Raised when a database write names a schema and key that no configured shard owns. Nothing was cached.
+ /// Raised when a database write, or a resolution, names a schema and key that no configured shard owns. A refused write
+ /// caches nothing.
///
public sealed class CultNetUnownedSchemaException : InvalidOperationException
{
@@ -655,7 +656,7 @@ namespace GameCult.Networking
{
ThrowIfDisposed();
var descriptor = _cache.Registry.GetRequired();
- return ResolveShardInternal(descriptor, key).IsPrimary;
+ return FindShard(descriptor, key)?.IsPrimary ?? false;
}
/// Gets whether this database instance can submit a prediction for the document at a key.
@@ -906,6 +907,7 @@ namespace GameCult.Networking
///
/// Resolves the shard that governs the supplied schema and key.
///
+ /// No configured shard owns the schema and key.
public CultNetShardDescriptor ResolveShard(string schemaId, CultRecordKey key)
{
ThrowIfDisposed();
@@ -957,7 +959,7 @@ namespace GameCult.Networking
if (document == null) throw new ArgumentNullException(nameof(document));
var descriptor = _cache.Registry.GetRequired(document.GetType());
- EnsurePrimary(OwningShard(descriptor, key), descriptor.SchemaId, key);
+ EnsurePrimary(ResolveShardInternal(descriptor, key), descriptor.SchemaId, key);
return await _cache.UpsertAsync(document, new CultRecordHandle(key)).ConfigureAwait(false);
}
@@ -993,7 +995,7 @@ namespace GameCult.Networking
{
ThrowIfDisposed();
var descriptor = _cache.Registry.GetRequired();
- EnsurePrimary(OwningShard(descriptor, key), descriptor.SchemaId, key);
+ EnsurePrimary(ResolveShardInternal(descriptor, key), descriptor.SchemaId, key);
_cache.Remove(new CultRecordHandle(key));
return Task.CompletedTask;
@@ -1199,7 +1201,13 @@ namespace GameCult.Networking
var door = TakeDoor(change);
var documentType = identity.GetType();
var descriptor = _cache.Registry.GetRequired(documentType);
- var shard = door?.Shard ?? ResolveShardInternal(descriptor, change.Key);
+ var shard = door?.Shard ?? FindShard(descriptor, change.Key);
+ if (shard == null)
+ {
+ // No shard owns a bare cache write of this schema: the database neither logs nor publishes it.
+ continue;
+ }
+
var kind = door?.Kind ?? change.Kind switch
{
CultCacheDocumentChangeKind.Removed => CultNetDatabaseChangeKind.Removed,
@@ -1222,9 +1230,8 @@ namespace GameCult.Networking
{
RecordReplicatedEntry(shard, logKind, descriptor.SchemaId, change, replicated);
}
- else if (door?.NoLog != true && shard.IsPrimary && (door != null || _shards.Any(candidate => candidate.Matches(descriptor, change.Key))))
+ else if (door?.NoLog != true && shard.IsPrimary)
{
- // A door chose its shard; a bare write belongs to a shard only when one matches it.
if (LogPrimaryChange(shard, logKind, descriptor.SchemaId, change, door) is { } burn)
{
(burned ??= new List()).Add(new CultNetBurnedSequence(shard.ShardId, burn.Sequence));
@@ -1864,20 +1871,6 @@ namespace GameCult.Networking
};
}
- private void EnsureClientAuthority(string schemaId, CultRecordKey key)
- {
- if (_clientAuthorityScopes.Any(scope => scope.Matches(_runtimeId, schemaId, key)))
- {
- return;
- }
-
- var shard = ResolveShardInternal(schemaId, key);
- throw new CultNetShardAuthorityException(
- shard,
- $"Runtime '{_runtimeId}' does not have client prediction authority for schema '{schemaId}' key '{key.Value}'.",
- "not_client_authority");
- }
-
private void EnsureClientAuthority(CultDocumentDescriptor descriptor, CultRecordKey key)
{
if (_clientAuthorityScopes.Any(scope => scope.Matches(_runtimeId, descriptor, key)))
@@ -1922,21 +1915,15 @@ namespace GameCult.Networking
}
}
- private CultNetShardDescriptor ResolveShardInternal(string schemaId, CultRecordKey key)
- {
- return _shards.FirstOrDefault(shard => shard.Matches(schemaId, key)) ?? _shards[0];
- }
+ // No shard owns a schema and key that no descriptor matches, and nothing is written to one: every write path refuses.
+ private CultNetShardDescriptor ResolveShardInternal(string schemaId, CultRecordKey key) =>
+ _shards.FirstOrDefault(shard => shard.Matches(schemaId, key)) ?? throw new CultNetUnownedSchemaException(schemaId, key);
- private CultNetShardDescriptor ResolveShardInternal(CultDocumentDescriptor descriptor, CultRecordKey key)
- {
- return _shards.FirstOrDefault(shard => shard.Matches(descriptor, key)) ?? _shards[0];
- }
+ private CultNetShardDescriptor ResolveShardInternal(CultDocumentDescriptor descriptor, CultRecordKey key) =>
+ FindShard(descriptor, key) ?? throw new CultNetUnownedSchemaException(descriptor.SchemaId, key);
- // The shard that owns the schema and key, for a write that carries no door and so cannot be placed by the wire message:
- // a write no shard owns would be cached and never logged, so it is refused.
- private CultNetShardDescriptor OwningShard(CultDocumentDescriptor descriptor, CultRecordKey key) =>
- _shards.FirstOrDefault(shard => shard.Matches(descriptor, key))
- ?? throw new CultNetUnownedSchemaException(descriptor.SchemaId, key);
+ private CultNetShardDescriptor? FindShard(CultDocumentDescriptor descriptor, CultRecordKey key) =>
+ _shards.FirstOrDefault(shard => shard.Matches(descriptor, key));
private static void EnsurePrimary(CultNetShardDescriptor shard, string schemaId, CultRecordKey key, long? expectedEpoch = null)
{
diff --git a/tests/GameCult.Networking.Tests/CultNetJournalTests.cs b/tests/GameCult.Networking.Tests/CultNetJournalTests.cs
index 806ad08b..5e18bcd7 100644
--- a/tests/GameCult.Networking.Tests/CultNetJournalTests.cs
+++ b/tests/GameCult.Networking.Tests/CultNetJournalTests.cs
@@ -614,46 +614,144 @@ namespace GameCult.Networking.Tests
}
[Test]
- public async Task ABareWriteOfASchemaNoShardOwnsIsNeitherLoggedNorReplicated()
+ public async Task ABareWriteOfASchemaNoShardOwnsIsNeitherLoggedNorPublishedNorReplicated()
{
var store = new FlakyLogStore();
var cache = new CultCache();
var database = Database(cache, primary: true, store);
+ var published = Record(database);
await cache.UpsertAsync(new MeshQuickstartNote { NoteId = "n", Body = "unrelated" }, new CultRecordHandle(new CultRecordKey("unrelated:n")));
await cache.UpsertAsync(Note("one"), new CultRecordHandle(One));
Assert.That(Sequences(store), Is.EqualTo(new[] { 1L }), "the unrelated write minted no sequence");
Assert.That(database.GetMutationLog(ShardId).Select(entry => entry.Key.Value), Is.EqualTo(new[] { One.Value }));
+ Assert.That(published, Is.EqualTo(new[] { One.Value }), "no shard owns the unrelated write, so the database does not publish it");
}
- // The database is the sharded write door: a write it cannot place in a shard is refused before anything is cached.
- // (An authoritative wire put carries a door that names its shard, and keeps the fallback shard.)
- [Test]
- public async Task ADatabaseWriteOfASchemaNoShardOwnsIsRefusedNamingTheSchemaAndAnAuthoritativePutKeepsTheFallbackShard()
+ // The database is the sharded write door: a schema and key no shard owns cannot be written on any path, and a refused
+ // write caches and logs nothing.
+ private static (CultNetDatabase Database, CultCache Cache, FlakyLogStore Store, string SchemaId) OwnedNothingOfNote()
{
var store = new FlakyLogStore();
var cache = new CultCache();
- var database = Database(cache, primary: true, store);
- var shard = database.Shards[0];
- var unowned = cache.Registry.GetRequired().SchemaId;
- var plainKey = new CultRecordKey("unrelated:plain");
+ return (Database(cache, primary: true, store), cache, store, cache.Registry.GetRequired().SchemaId);
+ }
+
+ private static readonly CultRecordKey Unowned = new("unrelated:note");
+
+ private static CultNetDocumentPutRawMessage UnownedPut(CultNetDatabase database)
+ {
+ var message = database.Documents.CreateRawDocumentPutMessage("wire", new CultRecordHandle(Unowned), new MeshQuickstartNote { NoteId = "w", Body = "wire" });
+ message.ShardId = database.Shards[0].ShardId;
+ message.ShardEpoch = database.Shards[0].Epoch;
+ return message;
+ }
+
+ [Test]
+ public void ADatabasePutOrDeleteOfASchemaNoShardOwnsIsRefusedNamingTheSchema()
+ {
+ var (database, cache, store, unowned) = OwnedNothingOfNote();
var put = Assert.ThrowsAsync(async () =>
- await database.PutAsync(plainKey, new MeshQuickstartNote { NoteId = "p", Body = "plain" }))!;
+ await database.PutAsync(Unowned, new MeshQuickstartNote { NoteId = "p", Body = "plain" }))!;
Assert.That(put.SchemaId, Is.EqualTo(unowned));
Assert.That(put.Message, Does.Contain(unowned));
Assert.That(put, Is.InstanceOf(), "a refused write reads as one");
- Assert.That(cache.Get(plainKey), Is.Null, "nothing was cached");
- Assert.ThrowsAsync(async () => await database.DeleteAsync(plainKey));
+ Assert.That(cache.Get(Unowned), Is.Null, "nothing was cached");
+ Assert.ThrowsAsync(async () => await database.DeleteAsync(Unowned));
Assert.That(Sequences(store), Is.Empty);
+ }
- var message = database.Documents.CreateRawDocumentPutMessage("door", new CultRecordHandle(new CultRecordKey("unrelated:door")), new MeshQuickstartNote { NoteId = "d", Body = "door" });
- message.ShardId = shard.ShardId;
- message.ShardEpoch = shard.Epoch;
- await database.ApplyPutAsync(message);
+ [Test]
+ public void ARemoteAuthoritativePutOfASchemaNoShardOwnsIsRefusedAndCachesNothing()
+ {
+ var (database, cache, store, unowned) = OwnedNothingOfNote();
- Assert.That(Sequences(store), Is.EqualTo(new[] { 1L }));
+ var refusal = Assert.ThrowsAsync(async () => await database.ApplyPutAsync(UnownedPut(database)))!;
+
+ Assert.That(refusal.SchemaId, Is.EqualTo(unowned));
+ Assert.That(cache.Get(Unowned), Is.Null);
+ Assert.That(Sequences(store), Is.Empty);
+ }
+
+ [Test]
+ public async Task ARemoteDeleteOfASchemaNoShardOwnsIsRefusedEvenWhenTheKeyIsCached()
+ {
+ var (database, cache, store, unowned) = OwnedNothingOfNote();
+ await cache.UpsertAsync(new MeshQuickstartNote { NoteId = "c", Body = "cached" }, new CultRecordHandle(Unowned));
+
+ var refusal = Assert.ThrowsAsync(async () => await database.ApplyDeleteAsync(new CultNetDocumentDeleteMessage
+ {
+ MessageId = "d",
+ SchemaId = unowned,
+ RecordKey = Unowned.Value,
+ ShardId = database.Shards[0].ShardId,
+ ShardEpoch = database.Shards[0].Epoch
+ }))!;
+
+ Assert.That(refusal.SchemaId, Is.EqualTo(unowned));
+ Assert.That(cache.Get(Unowned), Is.Not.Null, "the refused delete removed nothing");
+ Assert.That(Sequences(store), Is.Empty);
+ }
+
+ [Test]
+ public void APredictionOfASchemaNoShardOwnsIsRefused()
+ {
+ var cache = new CultCache();
+ var database = new CultNetDatabase(cache, new CultNetDatabaseOptions
+ {
+ RuntimeId = "local",
+ Shards = [new CultNetShardDescriptor("only-notes", "local", epoch: 1, isPrimary: true, schemaIds: [SchemaId(cache)])],
+ ClientAuthorityScopes = [new CultNetClientAuthorityScope("local")]
+ });
+
+ Assert.ThrowsAsync(async () =>
+ await database.PutPredictedAsync(Unowned, new MeshQuickstartNote { NoteId = "p", Body = "predicted" }));
+ Assert.That(cache.Get(Unowned), Is.Null);
+ }
+
+ [Test]
+ public void ASchemaNoShardOwnsCannotBeWrittenAuthoritativelyAndHasNoShardToResolve()
+ {
+ var (database, cache, _, unowned) = OwnedNothingOfNote();
+
+ Assert.That(database.CanWriteAuthoritatively(Unowned), Is.False);
+ Assert.That(database.CanWriteAuthoritatively(One), Is.True, "an owned schema is unaffected");
+ var refusal = Assert.Throws(() => database.ResolveShard(unowned, Unowned))!;
+ Assert.That(refusal.SchemaId, Is.EqualTo(unowned));
+ Assert.That(database.ResolveShard(SchemaId(cache), One).ShardId, Is.EqualTo(ShardId));
+ }
+
+ // The server answers a refused remote put the way it answers any other: it logs the failure and sends the peer a
+ // CultNetErrorMessage carrying the refusal. The handler is reached through its private delegate with an
+ // uninitialized peer, as the R-AM test does; the send then fails on that peer, after the failure was logged.
+ [Test]
+ public async Task TheServerAnswersARemotePutOfASchemaNoShardOwnsWithAnApplicationRejection()
+ {
+ var (database, cache, _, unowned) = OwnedNothingOfNote();
+ using var server = new Server(cache, ServerSecurityOptions.Development());
+ var logger = new CapturingLogger();
+ server.Logger = logger;
+ using var databaseServer = new CultNetDatabaseServer(server, database);
+ var handler = (Func)typeof(CultNetDatabaseServer)
+ .GetField("_putHandler", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)!
+ .GetValue(databaseServer)!;
+ var peer = (CultNetServerPeer)System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(CultNetServerPeer));
+
+ try { await handler(UnownedPut(database), peer); } catch (Exception) { }
+
+ Assert.That(logger.Errors, Has.Some.Contains("CultNet raw put failed").And.Contains(unowned));
+ Assert.That(cache.Get(Unowned), Is.Null);
+ }
+
+ private sealed class CapturingLogger : GameCult.Logging.ILogger
+ {
+ public List Errors { get; } = new();
+ public void LogInfo(string message) { }
+ public void LogWarning(string message) { }
+ public void LogError(string message) => Errors.Add(message);
+ public void LogDebug(string message) { }
}
private static async Task ApplyAuthoritativeAsync(CultNetDatabase database, CultRecordKey key, string text)