diff --git a/src/GameCult.Networking/CultNetDatabaseServer.cs b/src/GameCult.Networking/CultNetDatabaseServer.cs
index a6e55c3d..efe23be2 100644
--- a/src/GameCult.Networking/CultNetDatabaseServer.cs
+++ b/src/GameCult.Networking/CultNetDatabaseServer.cs
@@ -407,10 +407,10 @@ namespace GameCult.Networking
}
_server.Logger.LogWarning($"CultNet forwarded write was not answered by its primary: {failure.Message}");
- // Silence past the window means the primary may have applied it: never forward the id again on this session.
- // Any other failure never reached a primary that could have.
- if (failure is CultNetWriteUnconfirmedException) write.LeftSilent();
- else write.Unanswered();
+ // Only a forward that provably never left (not sent) may be forwarded again. Every other failure, silence or not, is
+ // unconfirmed: the primary may have applied it, so the id is never forwarded again on this session.
+ if (failure is CultNetWriteNotSentException) write.NotSent();
+ else write.LeftSilent();
}
private async Task HandlePutAsync(CultNetDocumentPutRawMessage message, CultNetServerPeer peer)
@@ -817,11 +817,14 @@ namespace GameCult.Networking
exception is CultNetShardLogException ||
exception is AggregateException aggregate && aggregate.Flatten().InnerExceptions.Any(inner => inner is CultNetShardLogException);
+ // Fixed text: the routing refusal never carries an exception's own message (the shard and reason travel in the hint).
+ internal const string RoutingRefusalText = "the write belongs to another shard primary";
+
private static CultNetErrorMessage CreateRoutingError(CultNetShardAuthorityException exception)
{
return new CultNetErrorMessage
{
- Error = exception.Message,
+ Error = RoutingRefusalText,
RoutingHint = new CultNetShardRoutingHint
{
Reason = exception.Reason,
diff --git a/src/GameCult.Networking/CultNetSchemaClient.cs b/src/GameCult.Networking/CultNetSchemaClient.cs
index 83865e31..79f0ce20 100644
--- a/src/GameCult.Networking/CultNetSchemaClient.cs
+++ b/src/GameCult.Networking/CultNetSchemaClient.cs
@@ -27,7 +27,8 @@ namespace GameCult.Networking
///
/// Sends one schema-v0 message through the transport. Fire-and-forget: an ack or a return is not admission;
- /// read the result frame ().
+ /// read the result frame (). Throws only
+ /// when it can prove no byte was written; any other exception leaves the send ambiguous and a forwarded write unconfirmed.
///
void SendCultNet(T message)
where T : ICultNetSchemaMessage;
diff --git a/src/GameCult.Networking/CultNetSchemaMessages.cs b/src/GameCult.Networking/CultNetSchemaMessages.cs
index 350ef43b..090c6a45 100644
--- a/src/GameCult.Networking/CultNetSchemaMessages.cs
+++ b/src/GameCult.Networking/CultNetSchemaMessages.cs
@@ -546,7 +546,7 @@ namespace GameCult.Networking
public static CultNetErrorMessage ForUnownedSchema(CultNetUnownedSchemaException ex) =>
new CultNetErrorMessage
{
- Error = $"unowned_schema: {ex.Message}",
+ Error = "unowned_schema: no shard owns the schema and key",
Code = "unowned_schema",
Details = new CultNetErrorDetails { Field = "schemaId", Value = ex.SchemaId }
};
diff --git a/src/GameCult.Networking/CultNetShardWriteForwarding.cs b/src/GameCult.Networking/CultNetShardWriteForwarding.cs
index cb390308..e4e66298 100644
--- a/src/GameCult.Networking/CultNetShardWriteForwarding.cs
+++ b/src/GameCult.Networking/CultNetShardWriteForwarding.cs
@@ -11,8 +11,9 @@ namespace GameCult.Networking
{
///
/// Forwards a raw document put to the shard owner. Completes only when the owner answered that it admitted the write;
- /// throws when it refused and
- /// when it answered nothing. The server relays to the original peer exactly what the owner answered.
+ /// throws when it refused, when
+ /// nothing could have reached it (the only failure after which the id may be forwarded again), and any other exception
+ /// when the frame may have gone out and was not answered (unconfirmed, including ). The server relays to the original peer exactly what the owner answered.
///
Task ForwardPutAsync(CultNetShardDescriptor shard, CultNetDocumentPutRawMessage message);
@@ -103,10 +104,10 @@ namespace GameCult.Networking
public async Task ForwardPutAsync(CultNetShardDescriptor shard, CultNetDocumentPutRawMessage message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
- var endpoint = ResolvePrimaryEndpoint(shard);
+ if (shard == null) throw new ArgumentNullException(nameof(shard));
message.ShardId ??= shard.ShardId;
message.ShardEpoch ??= shard.Epoch;
- await SendAsync(endpoint, message, message.MessageId).ConfigureAwait(false);
+ await SendAsync(shard, message, message.MessageId).ConfigureAwait(false);
}
///
@@ -116,10 +117,10 @@ namespace GameCult.Networking
public async Task ForwardDeleteAsync(CultNetShardDescriptor shard, CultNetDocumentDeleteMessage message)
{
if (message == null) throw new ArgumentNullException(nameof(message));
- var endpoint = ResolvePrimaryEndpoint(shard);
+ if (shard == null) throw new ArgumentNullException(nameof(shard));
message.ShardId ??= shard.ShardId;
message.ShardEpoch ??= shard.Epoch;
- await SendAsync(endpoint, message, message.MessageId).ConfigureAwait(false);
+ await SendAsync(shard, message, message.MessageId).ConfigureAwait(false);
}
///
@@ -143,19 +144,40 @@ namespace GameCult.Networking
return (uri.Host, uri.IsDefaultPort ? 3075 : uri.Port);
}
- private async Task SendAsync(string endpoint, T message, string messageId) where T : ICultNetSchemaMessage
+ // The write frame has not been handed to the transport until this returns: any failure here is CultNetWriteNotSentException,
+ // the one failure the caller may retry under the same id.
+ private async Task ConnectBeforeSendAsync(CultNetShardDescriptor shard, string messageId)
{
- var (host, port) = ParseEndpoint(endpoint);
- using var client = CreateClient(endpoint);
- client.Connect(host, port);
- await WaitForConnectionAsync(client, endpoint).ConfigureAwait(false);
- // The hello comes first on the ordered schema channel: it opts this connection in to the primary's receipts.
- client.SendCultNet(new CultNetHelloMessage
+ ICultNetSchemaClient? client = null;
+ try
{
- RuntimeId = "gamecult-networking-shard-forwarder",
- RuntimeKind = "dotnet",
- SupportedMessageVersions = [CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1]
- });
+ var endpoint = ResolvePrimaryEndpoint(shard);
+ var (host, port) = ParseEndpoint(endpoint);
+ client = CreateClient(endpoint);
+ client.Connect(host, port);
+ await WaitForConnectionAsync(client, endpoint).ConfigureAwait(false);
+ // The hello comes first on the ordered schema channel: it opts this connection in to the primary's receipts.
+ client.SendCultNet(new CultNetHelloMessage
+ {
+ RuntimeId = "gamecult-networking-shard-forwarder",
+ RuntimeKind = "dotnet",
+ SupportedMessageVersions = [CultNetSchemaVersions.WriteAdmitted, CultNetSchemaVersions.ErrorV1]
+ });
+ return client;
+ }
+ catch (Exception failure)
+ {
+ client?.Dispose();
+ if (failure is CultNetWriteNotSentException) throw;
+ throw new CultNetWriteNotSentException(messageId, failure);
+ }
+ }
+
+ private async Task SendAsync(CultNetShardDescriptor shard, T message, string messageId) where T : ICultNetSchemaMessage
+ {
+ using var client = await ConnectBeforeSendAsync(shard, messageId).ConfigureAwait(false);
+ // From the write's send on, every failure (timeout, reset, silence, an exception from the send itself) propagates as it
+ // is: the frame may have gone out, so the caller treats it as unconfirmed.
await CultNetWriteCompletion.SendAndAwaitReceiptAsync(
(admitted, refuse, refuseV1) =>
{
diff --git a/src/GameCult.Networking/CultNetWriteCompletion.cs b/src/GameCult.Networking/CultNetWriteCompletion.cs
index be8a4632..8767be6e 100644
--- a/src/GameCult.Networking/CultNetWriteCompletion.cs
+++ b/src/GameCult.Networking/CultNetWriteCompletion.cs
@@ -40,6 +40,24 @@ namespace GameCult.Networking
public string MessageId { get; }
}
+ ///
+ /// A forwarded write that provably never left this process: the connection failed, or the send failed before any byte was
+ /// written. It is the only forwarding failure after which the same id may be forwarded again. A send port that cannot prove
+ /// nothing was written must not throw this; every other failure of a forward is unconfirmed.
+ ///
+ public sealed class CultNetWriteNotSentException : Exception
+ {
+ /// Creates the exception for the write ; is for logs only.
+ public CultNetWriteNotSentException(string messageId, Exception? cause = null)
+ : base($"Write '{messageId}' was not sent.", cause)
+ {
+ MessageId = messageId;
+ }
+
+ /// Gets the id of the write that was not sent.
+ public string MessageId { get; }
+ }
+
///
/// Completes a write on the peer's result frame, never on a send's return or a transport acknowledgement:
/// an ack proves delivery, not admission.
diff --git a/src/GameCult.Networking/CultNetWriteReceipts.cs b/src/GameCult.Networking/CultNetWriteReceipts.cs
index 513efd99..cb13eeae 100644
--- a/src/GameCult.Networking/CultNetWriteReceipts.cs
+++ b/src/GameCult.Networking/CultNetWriteReceipts.cs
@@ -245,8 +245,8 @@ namespace GameCult.Networking
}
///
- /// A forward its primary left unanswered: no answer is owed or possible, and the claim stays so the id is never
- /// forwarded again on this session. Sends nothing.
+ /// A forward that may have reached its primary and is unconfirmed (silence, reset, timeout, an ambiguous send): no answer is
+ /// owed or possible, and the claim stays so the id is never forwarded again on this session. Sends nothing.
///
public void LeftSilent()
{
@@ -254,8 +254,8 @@ namespace GameCult.Networking
_answered = true;
}
- /// A forward that never reached a primary that could have applied it: forget the claim, send nothing.
- public void Unanswered()
+ /// A forward that was provably not sent (connect failed, or the send failed before any byte was written): forget the claim, send nothing.
+ public void NotSent()
{
if (_answered) return;
_answered = true;
diff --git a/tests/GameCult.Networking.Tests/CultNetWriteReceiptServerTests.cs b/tests/GameCult.Networking.Tests/CultNetWriteReceiptServerTests.cs
index b93b43b3..cab649e2 100644
--- a/tests/GameCult.Networking.Tests/CultNetWriteReceiptServerTests.cs
+++ b/tests/GameCult.Networking.Tests/CultNetWriteReceiptServerTests.cs
@@ -636,10 +636,9 @@ namespace GameCult.Networking.Tests
}
[Test]
- public async Task AForwardThatNeverReachedThePrimaryMayBeRetried()
+ public async Task AForwardThatWasNotSentMayBeRetriedUnderTheSameId()
{
- Exception failure = new TimeoutException("primary unreachable");
- var forwarder = new ScriptedForwarder { OnPut = _ => Task.FromException(failure) };
+ var forwarder = new ScriptedForwarder { OnPut = _ => Task.FromException(new CultNetWriteNotSentException("fwd-1", new TimeoutException("primary unreachable"))) };
var rig = Build(primary: false, forwarder: forwarder);
var wire = new Wire();
await rig.Hello(wire, BothFrames);
@@ -651,7 +650,176 @@ namespace GameCult.Networking.Tests
forwarder.OnPut = _ => Task.CompletedTask;
await rig.Put(wire, "fwd-1", KeyA, "one");
AssertAdmitted(wire.Sent.Single(), "fwd-1", "put", KeyA.Value);
- Assert.That(forwarder.Forwarded, Is.EqualTo(2), "the unanswered attempt left no claim behind");
+ Assert.That(forwarder.Forwarded, Is.EqualTo(2), "the unsent attempt left no claim behind");
+ }
+
+ // Once the frame may have gone out, whatever failed, the id is never forwarded again on the session.
+ private static IEnumerable PostSendFailures()
+ {
+ yield return new TestCaseData(new TimeoutException("no answer")).SetName("timeout");
+ yield return new TestCaseData(new System.IO.IOException("connection reset")).SetName("reset");
+ yield return new TestCaseData(new InvalidOperationException("client disconnected")).SetName("disconnected");
+ yield return new TestCaseData(new CultNetWriteUnconfirmedException("fwd-1")).SetName("no answer in the window");
+ yield return new TestCaseData(new Exception("anything else, ambiguous")).SetName("ambiguous");
+ }
+
+ [TestCaseSource(nameof(PostSendFailures))]
+ public async Task AForwardThatMayHaveBeenSentIsNeverForwardedAgainOnTheSession(Exception failure)
+ {
+ var forwarder = new ScriptedForwarder { OnPut = _ => Task.FromException(failure) };
+ var rig = Build(primary: false, forwarder: forwarder);
+ var wire = new Wire();
+ await rig.Hello(wire, BothFrames);
+ wire.Sent.Clear();
+
+ await rig.Put(wire, "fwd-1", KeyA, "one");
+ forwarder.OnPut = _ => Task.CompletedTask;
+ await rig.Put(wire, "fwd-1", KeyA, "one");
+
+ Assert.That(wire.Sent, Is.Empty, "unconfirmed: nothing answered, nothing synthesized");
+ Assert.That(forwarder.Forwarded, Is.EqualTo(1), "the claim stays");
+ }
+
+ [Test]
+ public async Task TheRealForwarderRetriesAConnectFailureButNotAFailureAfterTheWriteWasSent()
+ {
+ var clients = new Queue();
+ var forwarder = new CultNetSchemaWriteForwarder(new CultNetSchemaWriteForwarderOptions
+ {
+ CreateClient = () => clients.Dequeue(),
+ ConnectTimeout = TimeSpan.FromMilliseconds(100),
+ ResultWindow = TimeSpan.FromMilliseconds(100)
+ });
+ var rig = Build(primary: false, forwarder: forwarder);
+ var wire = new Wire();
+ await rig.Hello(wire, BothFrames);
+ wire.Sent.Clear();
+
+ clients.Enqueue(new ForwardingClient { ConnectFails = true });
+ await rig.Put(wire, "fwd-1", KeyA, "one");
+ var sent = new ForwardingClient { AdmitWrites = true };
+ clients.Enqueue(sent);
+ await rig.Put(wire, "fwd-1", KeyA, "one");
+ AssertAdmitted(wire.Sent.Single(), "fwd-1", "put", KeyA.Value);
+
+ wire.Sent.Clear();
+ var reset = new ForwardingClient { WriteSendFails = true };
+ clients.Enqueue(reset);
+ await rig.Put(wire, "fwd-2", KeyA, "two");
+ clients.Enqueue(new ForwardingClient { AdmitWrites = true });
+ await rig.Put(wire, "fwd-2", KeyA, "two");
+ Assert.That(wire.Sent, Is.Empty, "the write send threw: it may have gone out");
+ Assert.That(clients, Has.Count.EqualTo(1), "and the id was not forwarded again");
+ }
+
+ private sealed class ForwardingClient : ICultNetSchemaClient
+ {
+ private Action? _admitted;
+ public bool ConnectFails { get; set; }
+ public bool NeverConnects { get; set; }
+ public bool HelloSendFails { get; set; }
+ public bool WriteSendFails { get; set; }
+ public bool WriteNotSentFails { get; set; }
+ public bool AdmitWrites { get; set; }
+ public bool Connected { get; private set; }
+ public List Sent { get; } = new();
+
+ public void Connect(string host, int port)
+ {
+ if (ConnectFails) throw new System.Net.Sockets.SocketException();
+ Connected = !NeverConnects;
+ }
+
+ public void SendCultNet(T message) where T : ICultNetSchemaMessage
+ {
+ if (message is CultNetHelloMessage)
+ {
+ if (HelloSendFails) throw new System.IO.IOException("hello failed");
+ return;
+ }
+
+ if (WriteNotSentFails) throw new CultNetWriteNotSentException("x");
+ if (WriteSendFails) throw new System.IO.IOException("send failed after an unknown number of bytes");
+ Sent.Add(message);
+ if (AdmitWrites && message is CultNetDocumentPutRawMessage put)
+ _admitted?.Invoke(new CultNetWriteAdmittedMessage { MessageId = put.MessageId, Operation = "put", SchemaId = put.Document?.SchemaId, RecordKey = put.Document?.RecordKey });
+ }
+
+ public void OnCultNet(Action callback) where T : ICultNetSchemaMessage
+ {
+ if (callback is Action admitted) _admitted = admitted;
+ }
+
+ public void Dispose() { }
+ }
+
+ private static CultNetSchemaWriteForwarder RealForwarder(ForwardingClient client) => new(new CultNetSchemaWriteForwarderOptions
+ {
+ CreateClient = () => client,
+ ConnectTimeout = TimeSpan.FromMilliseconds(100),
+ ResultWindow = TimeSpan.FromMilliseconds(100)
+ });
+
+ private static readonly CultNetShardDescriptor ForwardShard = new("notes", "primary", 1, isPrimary: false, primaryEndpoints: ["cultnet://primary.example.test:4075"]);
+
+ private static CultNetDocumentPutRawMessage ForwardPut() => new() { MessageId = "fwd-1", Document = new CultNetRawDocumentRecord { SchemaId = "s", RecordKey = "k", Payload = [1] } };
+
+ [TestCase("connect")]
+ [TestCase("never connects")]
+ [TestCase("hello")]
+ [TestCase("write not sent")]
+ public void TheForwarderNamesEveryFailureBeforeTheWriteWasSentAsNotSent(string stage)
+ {
+ var client = new ForwardingClient
+ {
+ ConnectFails = stage == "connect",
+ NeverConnects = stage == "never connects",
+ HelloSendFails = stage == "hello",
+ WriteNotSentFails = stage == "write not sent"
+ };
+
+ Assert.ThrowsAsync(() => RealForwarder(client).ForwardPutAsync(ForwardShard, ForwardPut()));
+ Assert.That(client.Sent, Is.Empty);
+ }
+
+ [Test]
+ public void TheForwarderNamesNoPrimaryEndpointAsNotSent()
+ {
+ var shard = new CultNetShardDescriptor("notes", "primary", 1, isPrimary: false, primaryEndpoints: []);
+ Assert.ThrowsAsync(() => RealForwarder(new ForwardingClient()).ForwardPutAsync(shard, ForwardPut()));
+ }
+
+ [Test]
+ public void ASendThatThrewWithoutProvingNothingWasWrittenIsNotNotSent()
+ {
+ var client = new ForwardingClient { WriteSendFails = true };
+ var failure = Assert.CatchAsync(() => RealForwarder(client).ForwardPutAsync(ForwardShard, ForwardPut()));
+ Assert.That(failure, Is.Not.InstanceOf(), "ambiguous: unconfirmed");
+ }
+
+ [Test]
+ public void ASentWriteNobodyAnswersIsUnconfirmedNotNotSent()
+ {
+ var client = new ForwardingClient();
+ Assert.ThrowsAsync(() => RealForwarder(client).ForwardPutAsync(ForwardShard, ForwardPut()));
+ Assert.That(client.Sent, Has.Count.EqualTo(1));
+ }
+
+ [Test]
+ public async Task TheRoutingRefusalAndTheUnownedSchemaRefusalCarryNoExceptionText()
+ {
+ var rig = Build(primary: false);
+ var wire = new Wire();
+ await rig.Hello(wire, BothFrames);
+ wire.Sent.Clear();
+ await rig.Put(wire, "fwd-1", KeyA, "one");
+ var routing = AssertRefused(wire.Sent.Single(), "fwd-1", null);
+ Assert.That(routing.Error, Is.EqualTo(CultNetDatabaseServer.RoutingRefusalText));
+
+ var secret = new CultNetUnownedSchemaException("secret.schema.v1", new CultRecordKey("secret:key"));
+ var unowned = CultNetErrorMessage.ForUnownedSchema(secret);
+ Assert.That(unowned.Error, Does.Not.Contain(secret.Message).And.Not.Contain("secret"));
+ Assert.That(unowned.Details!.Value, Is.EqualTo("secret.schema.v1"), "the structured detail still names the schema");
}
[Test]