diff --git a/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs b/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs index d098a923..cdcca912 100644 --- a/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs +++ b/src/GameCult.Networking/CultNetSchemaMessageSerialization.cs @@ -53,6 +53,8 @@ namespace GameCult.Networking CultNetSchemaVersions.Verify => Deserialize(payload), CultNetSchemaVersions.LoginSuccess => Deserialize(payload), CultNetSchemaVersions.Error => Deserialize(payload), + CultNetSchemaVersions.ErrorV1 => Deserialize(payload), + CultNetSchemaVersions.WriteAdmitted => Deserialize(payload), CultNetSchemaVersions.SampleChangeName => Deserialize(payload), CultNetSchemaVersions.SampleChat => Deserialize(payload), CultNetSchemaVersions.OperationRequest => Deserialize(payload), diff --git a/src/GameCult.Networking/CultNetSchemaMessages.cs b/src/GameCult.Networking/CultNetSchemaMessages.cs index 5f37f150..0a3f9adb 100644 --- a/src/GameCult.Networking/CultNetSchemaMessages.cs +++ b/src/GameCult.Networking/CultNetSchemaMessages.cs @@ -48,6 +48,14 @@ namespace GameCult.Networking /// public const string Error = "cultnet.error.v0"; /// + /// error v1 contract identifier: error v0 plus the id of the request it answers (write-receipt.md). + /// + public const string ErrorV1 = "cultnet.error.v1"; + /// + /// write admitted receipt contract identifier (write-receipt.md). + /// + public const string WriteAdmitted = "cultnet.write_admitted.v0"; + /// /// sample change name contract identifier. /// public const string SampleChangeName = "cultnet.sample.change_name.v0"; @@ -621,6 +629,68 @@ namespace GameCult.Networking }; } + /// + /// cultnet.error.v1 (contracts/cultnet/interop/write-receipt.md): the v0 error plus , + /// the id of the request it answers. Sent only to a connection that declared the write-receipt capability. + /// + [MessagePackObject] + public class CultNetErrorV1Message : ICultNetSchemaMessage + { + /// Gets or sets the schema version. + [Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ErrorV1; + /// Gets or sets the error. + [Key("error")] public string Error { get; set; } = string.Empty; + /// Gets or sets optional shard routing details for authority failures. + [Key("routingHint")] public CultNetShardRoutingHint? RoutingHint { get; set; } + /// Gets or sets the machine-readable refusal code (the v0 enum). + [Key("code")] public string? Code { get; set; } + /// Gets or sets the code-specific structured detail. + [Key("details")] public CultNetErrorDetails? Details { get; set; } + /// Gets or sets the id of the request this answers; null only when no id could be read. + [Key("messageId")] public string? MessageId { get; set; } + + /// Builds the v1 form of answering . + public static CultNetErrorV1Message From(CultNetErrorMessage error, string? messageId) + { + if (error == null) throw new ArgumentNullException(nameof(error)); + return new CultNetErrorV1Message + { + Error = error.Error, + RoutingHint = error.RoutingHint, + Code = error.Code, + Details = error.Details, + MessageId = string.IsNullOrEmpty(messageId) ? null : messageId + }; + } + + /// Gets the v0 form, dropping the id. + public CultNetErrorMessage ToV0() => new CultNetErrorMessage + { + Error = Error, + RoutingHint = RoutingHint, + Code = Code, + Details = Details + }; + } + + /// + /// cultnet.write_admitted.v0: the receipt for one admitted put or delete, sent after its commit point. + /// + [MessagePackObject] + public class CultNetWriteAdmittedMessage : ICultNetSchemaMessage + { + /// Gets or sets the schema version. + [Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.WriteAdmitted; + /// Gets or sets the messageId of the admitted write, echoed. + [Key("messageId")] public string MessageId { get; set; } = string.Empty; + /// Gets or sets put or delete. + [Key("operation")] public string Operation { get; set; } = string.Empty; + /// Gets or sets the schemaId of the admitted write, echoed. + [Key("schemaId")] public string SchemaId { get; set; } = string.Empty; + /// Gets or sets the recordKey of the admitted write, echoed. + [Key("recordKey")] public string RecordKey { get; set; } = string.Empty; + } + /// /// Code-specific structured detail carried on (R-N). Fields are /// populated only for the code that defines them; every field is otherwise omitted (nil on the wire). diff --git a/src/GameCult.Networking/CultNetWriteCompletion.cs b/src/GameCult.Networking/CultNetWriteCompletion.cs index 6d5c226d..be8a4632 100644 --- a/src/GameCult.Networking/CultNetWriteCompletion.cs +++ b/src/GameCult.Networking/CultNetWriteCompletion.cs @@ -24,6 +24,22 @@ namespace GameCult.Networking public CultNetErrorMessage Refusal { get; } } + /// + /// A write nothing answered within its window: neither admitted nor refused (write-receipt.md, "unconfirmed"). + /// + public sealed class CultNetWriteUnconfirmedException : Exception + { + /// Creates the exception for the write . + public CultNetWriteUnconfirmedException(string messageId) + : base($"No admission or refusal arrived for write '{messageId}'.") + { + MessageId = messageId; + } + + /// Gets the id of the unconfirmed write. + 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. @@ -33,6 +49,49 @@ namespace GameCult.Networking /// How long after a send a refusal may still arrive when the caller names no window. public static readonly TimeSpan DefaultResultWindow = TimeSpan.FromMilliseconds(500); + /// How long a receipt-capable peer has to answer a write (write-receipt.md, RECEIPT_RESULT_WINDOW_MS). + public static readonly TimeSpan ReceiptResultWindow = TimeSpan.FromMilliseconds(5000); + + /// + /// Sends one write to a receipt-capable peer and waits for its answer: a + /// write_admitted naming returns, an error.v1 naming it throws + /// , and an id-less error (v0, or v1 with no id) is attributed to this write + /// because it is the only one in flight on the connection. Silence throws . + /// + public static async Task SendAndAwaitReceiptAsync( + Func, Action, Action, IDisposable?> subscribe, + Action send, + string messageId, + TimeSpan resultWindow, + CancellationToken cancellationToken = default) + { + if (subscribe == null) throw new ArgumentNullException(nameof(subscribe)); + if (send == null) throw new ArgumentNullException(nameof(send)); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var registration = subscribe( + admitted => + { + if (string.Equals(admitted.MessageId, messageId, StringComparison.Ordinal)) answer.TrySetResult(null); + }, + error => answer.TrySetResult(error), + error => + { + if (error.MessageId == null || string.Equals(error.MessageId, messageId, StringComparison.Ordinal)) + answer.TrySetResult(error.ToV0()); + }); + send(); + var window = Task.Delay(resultWindow, cancellationToken); + await Task.WhenAny(answer.Task, window).ConfigureAwait(false); + if (!answer.Task.IsCompleted) + { + await window.ConfigureAwait(false); + throw new CultNetWriteUnconfirmedException(messageId); + } + + var refusal = await answer.Task.ConfigureAwait(false); + if (refusal != null) throw new CultNetWriteRefusedException(refusal); + } + /// /// Sends one write and waits for the peer's answer. A refusal frame rejects with /// whatever its order against the transport acknowledgement. A peer diff --git a/src/GameCult.Networking/CultNetWriteReceipts.cs b/src/GameCult.Networking/CultNetWriteReceipts.cs new file mode 100644 index 00000000..2cc65db8 --- /dev/null +++ b/src/GameCult.Networking/CultNetWriteReceipts.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using MessagePack; + +namespace GameCult.Networking +{ + /// + /// The content hash a write-receipt server binds to a (peer, messageId) dedupe key + /// (contracts/cultnet/interop/write-receipt.md, rule 5). + /// + public static class CultNetWriteContentHash + { + /// + /// SHA-256 of the MessagePack array [operation, schemaId, recordKey, payload], payload a bin + /// for a put and nil for a delete. + /// + public static byte[] Compute(string operation, string schemaId, string recordKey, byte[]? payload) + { + var buffer = new System.Buffers.ArrayBufferWriter(); + var writer = new MessagePackWriter(buffer); + writer.WriteArrayHeader(4); + writer.Write(operation); + writer.Write(schemaId); + writer.Write(recordKey); + if (payload == null) writer.WriteNil(); + else writer.Write(payload); + writer.Flush(); + return SHA256.HashData(buffer.WrittenSpan); + } + } + + /// + /// Whether a peer's hello opted in to write receipts: it lists both cultnet.write_admitted.v0 and + /// cultnet.error.v1. The capability changes framing only; it never authorizes. + /// + internal static class CultNetWriteReceiptCapability + { + public static bool Declares(CultNetHelloMessage hello) + { + var versions = hello.SupportedMessageVersions; + return versions != null + && Array.IndexOf(versions, CultNetSchemaVersions.WriteAdmitted) >= 0 + && Array.IndexOf(versions, CultNetSchemaVersions.ErrorV1) >= 0; + } + } + + /// + /// One receipt-capable peer's writes: message id to content hash, so a resend of the same content is re-receipted + /// without being committed again and the same id with other content is refused. + /// + internal sealed class CultNetWriteReceiptSession + { + /// The most writes a peer is remembered for; a peer at the limit has new writes refused. + internal const int MaxRememberedWrites = 1024; + + private readonly object _gate = new(); + private readonly Dictionary _writes = new(StringComparer.Ordinal); + + private sealed class Entry + { + public Entry(byte[] hash) { Hash = hash; } + public byte[] Hash { get; } + public bool Admitted { get; set; } + } + + public enum Begin { New, AdmittedBefore, InFlight, DifferentContent, Full } + + /// Claims for a write with this content, or says what already holds it. + public Begin TryBegin(string messageId, byte[] hash) + { + lock (_gate) + { + if (_writes.TryGetValue(messageId, out var entry)) + { + if (!CryptographicOperations.FixedTimeEquals(entry.Hash, hash)) return Begin.DifferentContent; + return entry.Admitted ? Begin.AdmittedBefore : Begin.InFlight; + } + + if (_writes.Count >= MaxRememberedWrites) return Begin.Full; + _writes[messageId] = new Entry(hash); + return Begin.New; + } + } + + /// The write committed: remember it so a resend is re-receipted. + public void Admitted(string messageId) + { + lock (_gate) + { + if (_writes.TryGetValue(messageId, out var entry)) entry.Admitted = true; + } + } + + /// The write was refused or unanswered: forget it so a corrected or repeated attempt is judged afresh. + public void Abandoned(string messageId) + { + lock (_gate) + { + _writes.Remove(messageId); + } + } + } +}