C#: a forward is retryable only when provably not sent; unconfirmed otherwise; refusals carry fixed text
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultNetWriteNotSentException names the pre-send boundary (connect, hello, no endpoint, or a send port that proves nothing was written). Every other forwarding failure keeps the session claim. ForUnownedSchema and the routing refusal no longer carry exception text. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2e5df24e96
commit
541d734675
7 changed files with 244 additions and 32 deletions
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -27,7 +27,8 @@ namespace GameCult.Networking
|
|||
|
||||
/// <summary>
|
||||
/// Sends one schema-v0 message through the transport. Fire-and-forget: an ack or a return is not admission;
|
||||
/// read the result frame (<see cref="CultNetWriteCompletion"/>).
|
||||
/// read the result frame (<see cref="CultNetWriteCompletion"/>). Throws <see cref="CultNetWriteNotSentException"/> only
|
||||
/// when it can prove no byte was written; any other exception leaves the send ambiguous and a forwarded write unconfirmed.
|
||||
/// </summary>
|
||||
void SendCultNet<T>(T message)
|
||||
where T : ICultNetSchemaMessage;
|
||||
|
|
|
|||
|
|
@ -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 }
|
||||
};
|
||||
|
|
|
|||
|
|
@ -11,8 +11,9 @@ namespace GameCult.Networking
|
|||
{
|
||||
/// <summary>
|
||||
/// Forwards a raw document put to the shard owner. Completes only when the owner answered that it admitted the write;
|
||||
/// throws <see cref="CultNetWriteRefusedException"/> when it refused and <see cref="CultNetWriteUnconfirmedException"/>
|
||||
/// when it answered nothing. The server relays to the original peer exactly what the owner answered.
|
||||
/// throws <see cref="CultNetWriteRefusedException"/> when it refused, <see cref="CultNetWriteNotSentException"/> 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 <see cref="CultNetWriteUnconfirmedException"/>). The server relays to the original peer exactly what the owner answered.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -143,19 +144,40 @@ namespace GameCult.Networking
|
|||
return (uri.Host, uri.IsDefaultPort ? 3075 : uri.Port);
|
||||
}
|
||||
|
||||
private async Task SendAsync<T>(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<ICultNetSchemaClient> 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<T>(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) =>
|
||||
{
|
||||
|
|
|
|||
|
|
@ -40,6 +40,24 @@ namespace GameCult.Networking
|
|||
public string MessageId { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class CultNetWriteNotSentException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception for the write <paramref name="messageId"/>; <paramref name="cause"/> is for logs only.</summary>
|
||||
public CultNetWriteNotSentException(string messageId, Exception? cause = null)
|
||||
: base($"Write '{messageId}' was not sent.", cause)
|
||||
{
|
||||
MessageId = messageId;
|
||||
}
|
||||
|
||||
/// <summary>Gets the id of the write that was not sent.</summary>
|
||||
public string MessageId { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
|
|
|
|||
|
|
@ -245,8 +245,8 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public void LeftSilent()
|
||||
{
|
||||
|
|
@ -254,8 +254,8 @@ namespace GameCult.Networking
|
|||
_answered = true;
|
||||
}
|
||||
|
||||
/// <summary>A forward that never reached a primary that could have applied it: forget the claim, send nothing.</summary>
|
||||
public void Unanswered()
|
||||
/// <summary>A forward that was provably not sent (connect failed, or the send failed before any byte was written): forget the claim, send nothing.</summary>
|
||||
public void NotSent()
|
||||
{
|
||||
if (_answered) return;
|
||||
_answered = true;
|
||||
|
|
|
|||
|
|
@ -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<TestCaseData> 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<ForwardingClient>();
|
||||
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<CultNetWriteAdmittedMessage>? _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<ICultNetSchemaMessage> Sent { get; } = new();
|
||||
|
||||
public void Connect(string host, int port)
|
||||
{
|
||||
if (ConnectFails) throw new System.Net.Sockets.SocketException();
|
||||
Connected = !NeverConnects;
|
||||
}
|
||||
|
||||
public void SendCultNet<T>(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<T>(Action<T> callback) where T : ICultNetSchemaMessage
|
||||
{
|
||||
if (callback is Action<CultNetWriteAdmittedMessage> 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<CultNetWriteNotSentException>(() => 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<CultNetWriteNotSentException>(() => RealForwarder(new ForwardingClient()).ForwardPutAsync(shard, ForwardPut()));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASendThatThrewWithoutProvingNothingWasWrittenIsNotNotSent()
|
||||
{
|
||||
var client = new ForwardingClient { WriteSendFails = true };
|
||||
var failure = Assert.CatchAsync<Exception>(() => RealForwarder(client).ForwardPutAsync(ForwardShard, ForwardPut()));
|
||||
Assert.That(failure, Is.Not.InstanceOf<CultNetWriteNotSentException>(), "ambiguous: unconfirmed");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASentWriteNobodyAnswersIsUnconfirmedNotNotSent()
|
||||
{
|
||||
var client = new ForwardingClient();
|
||||
Assert.ThrowsAsync<CultNetWriteUnconfirmedException>(() => 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]
|
||||
|
|
|
|||
Loading…
Reference in a new issue