WIP C# write-receipt server (not built, not tested): messages, content hash, per-peer dedupe state, receipt-aware wait
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
dc5abedffc
commit
45e95984e5
4 changed files with 235 additions and 0 deletions
|
|
@ -53,6 +53,8 @@ namespace GameCult.Networking
|
|||
CultNetSchemaVersions.Verify => Deserialize<CultNetVerifyMessage>(payload),
|
||||
CultNetSchemaVersions.LoginSuccess => Deserialize<CultNetLoginSuccessMessage>(payload),
|
||||
CultNetSchemaVersions.Error => Deserialize<CultNetErrorMessage>(payload),
|
||||
CultNetSchemaVersions.ErrorV1 => Deserialize<CultNetErrorV1Message>(payload),
|
||||
CultNetSchemaVersions.WriteAdmitted => Deserialize<CultNetWriteAdmittedMessage>(payload),
|
||||
CultNetSchemaVersions.SampleChangeName => Deserialize<CultNetSampleChangeNameMessage>(payload),
|
||||
CultNetSchemaVersions.SampleChat => Deserialize<CultNetSampleChatMessage>(payload),
|
||||
CultNetSchemaVersions.OperationRequest => Deserialize<CultNetOperationRequestMessage>(payload),
|
||||
|
|
|
|||
|
|
@ -48,6 +48,14 @@ namespace GameCult.Networking
|
|||
/// </summary>
|
||||
public const string Error = "cultnet.error.v0";
|
||||
/// <summary>
|
||||
/// error v1 contract identifier: error v0 plus the id of the request it answers (write-receipt.md).
|
||||
/// </summary>
|
||||
public const string ErrorV1 = "cultnet.error.v1";
|
||||
/// <summary>
|
||||
/// write admitted receipt contract identifier (write-receipt.md).
|
||||
/// </summary>
|
||||
public const string WriteAdmitted = "cultnet.write_admitted.v0";
|
||||
/// <summary>
|
||||
/// sample change name contract identifier.
|
||||
/// </summary>
|
||||
public const string SampleChangeName = "cultnet.sample.change_name.v0";
|
||||
|
|
@ -621,6 +629,68 @@ namespace GameCult.Networking
|
|||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>cultnet.error.v1</c> (contracts/cultnet/interop/write-receipt.md): the v0 error plus <see cref="MessageId"/>,
|
||||
/// the id of the request it answers. Sent only to a connection that declared the write-receipt capability.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultNetErrorV1Message : ICultNetSchemaMessage
|
||||
{
|
||||
/// <summary>Gets or sets the schema version.</summary>
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.ErrorV1;
|
||||
/// <summary>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>Gets or sets the machine-readable refusal code (the v0 enum).</summary>
|
||||
[Key("code")] public string? Code { get; set; }
|
||||
/// <summary>Gets or sets the code-specific structured detail.</summary>
|
||||
[Key("details")] public CultNetErrorDetails? Details { get; set; }
|
||||
/// <summary>Gets or sets the id of the request this answers; null only when no id could be read.</summary>
|
||||
[Key("messageId")] public string? MessageId { get; set; }
|
||||
|
||||
/// <summary>Builds the v1 form of <paramref name="error"/> answering <paramref name="messageId"/>.</summary>
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Gets the v0 form, dropping the id.</summary>
|
||||
public CultNetErrorMessage ToV0() => new CultNetErrorMessage
|
||||
{
|
||||
Error = Error,
|
||||
RoutingHint = RoutingHint,
|
||||
Code = Code,
|
||||
Details = Details
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>cultnet.write_admitted.v0</c>: the receipt for one admitted put or delete, sent after its commit point.
|
||||
/// </summary>
|
||||
[MessagePackObject]
|
||||
public class CultNetWriteAdmittedMessage : ICultNetSchemaMessage
|
||||
{
|
||||
/// <summary>Gets or sets the schema version.</summary>
|
||||
[Key("schemaVersion")] public string SchemaVersion { get; set; } = CultNetSchemaVersions.WriteAdmitted;
|
||||
/// <summary>Gets or sets the messageId of the admitted write, echoed.</summary>
|
||||
[Key("messageId")] public string MessageId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets <c>put</c> or <c>delete</c>.</summary>
|
||||
[Key("operation")] public string Operation { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the schemaId of the admitted write, echoed.</summary>
|
||||
[Key("schemaId")] public string SchemaId { get; set; } = string.Empty;
|
||||
/// <summary>Gets or sets the recordKey of the admitted write, echoed.</summary>
|
||||
[Key("recordKey")] public string RecordKey { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Code-specific structured detail carried on <see cref="CultNetErrorMessage"/> (R-N). Fields are
|
||||
/// populated only for the code that defines them; every field is otherwise omitted (nil on the wire).
|
||||
|
|
|
|||
|
|
@ -24,6 +24,22 @@ namespace GameCult.Networking
|
|||
public CultNetErrorMessage Refusal { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A write nothing answered within its window: neither admitted nor refused (write-receipt.md, "unconfirmed").
|
||||
/// </summary>
|
||||
public sealed class CultNetWriteUnconfirmedException : Exception
|
||||
{
|
||||
/// <summary>Creates the exception for the write <paramref name="messageId"/>.</summary>
|
||||
public CultNetWriteUnconfirmedException(string messageId)
|
||||
: base($"No admission or refusal arrived for write '{messageId}'.")
|
||||
{
|
||||
MessageId = messageId;
|
||||
}
|
||||
|
||||
/// <summary>Gets the id of the unconfirmed write.</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.
|
||||
|
|
@ -33,6 +49,49 @@ namespace GameCult.Networking
|
|||
/// <summary>How long after a send a refusal may still arrive when the caller names no window.</summary>
|
||||
public static readonly TimeSpan DefaultResultWindow = TimeSpan.FromMilliseconds(500);
|
||||
|
||||
/// <summary>How long a receipt-capable peer has to answer a write (write-receipt.md, <c>RECEIPT_RESULT_WINDOW_MS</c>).</summary>
|
||||
public static readonly TimeSpan ReceiptResultWindow = TimeSpan.FromMilliseconds(5000);
|
||||
|
||||
/// <summary>
|
||||
/// Sends one write to a receipt-capable peer and waits <paramref name="resultWindow"/> for its answer: a
|
||||
/// <c>write_admitted</c> naming <paramref name="messageId"/> returns, an <c>error.v1</c> naming it throws
|
||||
/// <see cref="CultNetWriteRefusedException"/>, 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 <see cref="CultNetWriteUnconfirmedException"/>.
|
||||
/// </summary>
|
||||
public static async Task SendAndAwaitReceiptAsync(
|
||||
Func<Action<CultNetWriteAdmittedMessage>, Action<CultNetErrorMessage>, Action<CultNetErrorV1Message>, 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<CultNetErrorMessage?>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends one write and waits <paramref name="resultWindow"/> for the peer's answer. A refusal frame rejects with
|
||||
/// <see cref="CultNetWriteRefusedException"/> whatever its order against the transport acknowledgement. A peer
|
||||
|
|
|
|||
104
src/GameCult.Networking/CultNetWriteReceipts.cs
Normal file
104
src/GameCult.Networking/CultNetWriteReceipts.cs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Security.Cryptography;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
/// <summary>
|
||||
/// The content hash a write-receipt server binds to a (peer, messageId) dedupe key
|
||||
/// (contracts/cultnet/interop/write-receipt.md, rule 5).
|
||||
/// </summary>
|
||||
public static class CultNetWriteContentHash
|
||||
{
|
||||
/// <summary>
|
||||
/// SHA-256 of the MessagePack array <c>[operation, schemaId, recordKey, payload]</c>, <c>payload</c> a <c>bin</c>
|
||||
/// for a put and nil for a delete.
|
||||
/// </summary>
|
||||
public static byte[] Compute(string operation, string schemaId, string recordKey, byte[]? payload)
|
||||
{
|
||||
var buffer = new System.Buffers.ArrayBufferWriter<byte>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether a peer's hello opted in to write receipts: it lists both <c>cultnet.write_admitted.v0</c> and
|
||||
/// <c>cultnet.error.v1</c>. The capability changes framing only; it never authorizes.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class CultNetWriteReceiptSession
|
||||
{
|
||||
/// <summary>The most writes a peer is remembered for; a peer at the limit has new writes refused.</summary>
|
||||
internal const int MaxRememberedWrites = 1024;
|
||||
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, Entry> _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 }
|
||||
|
||||
/// <summary>Claims <paramref name="messageId"/> for a write with this content, or says what already holds it.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The write committed: remember it so a resend is re-receipted.</summary>
|
||||
public void Admitted(string messageId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (_writes.TryGetValue(messageId, out var entry)) entry.Admitted = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The write was refused or unanswered: forget it so a corrected or repeated attempt is judged afresh.</summary>
|
||||
public void Abandoned(string messageId)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_writes.Remove(messageId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue