using System;
using System.Threading;
using System.Threading.Tasks;
namespace GameCult.Networking
{
///
/// A peer refused a write: the typed cultnet.error.v0 it answered with.
///
public sealed class CultNetWriteRefusedException : Exception
{
/// Creates the exception from the refusal frame.
public CultNetWriteRefusedException(CultNetErrorMessage refusal)
: base(refusal?.Error ?? throw new ArgumentNullException(nameof(refusal)))
{
Code = refusal.Code;
Refusal = refusal;
}
/// Gets the machine-readable refusal code, e.g. write_not_authorized or message_invalid.
public string? Code { get; }
/// Gets the refusal frame as received.
public CultNetErrorMessage Refusal { 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.
///
public static class CultNetWriteCompletion
{
/// How long after a send a refusal may still arrive when the caller names no window.
public static readonly TimeSpan DefaultResultWindow = TimeSpan.FromMilliseconds(500);
///
/// Sends one write and waits for the peer's answer. A refusal frame rejects with
/// whatever its order against the transport acknowledgement. A peer
/// that admits a write sends no success frame, so the end of the window is the interim bound on a refusal
/// (until peers send one); the error frame carries no message id, so any refusal inside the window is this
/// write's.
///
/// Registers the refusal handler and returns its registration; called before the send.
/// Sends the write.
/// How long a refusal may take to arrive.
/// Cancels the wait.
public static async Task SendAndAwaitResultAsync(
Func, IDisposable?> subscribe,
Action send,
TimeSpan resultWindow,
CancellationToken cancellationToken = default)
{
if (subscribe == null) throw new ArgumentNullException(nameof(subscribe));
if (send == null) throw new ArgumentNullException(nameof(send));
var refused = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
using var registration = subscribe(error => refused.TrySetResult(error));
send();
var window = Task.Delay(resultWindow, cancellationToken);
await Task.WhenAny(refused.Task, window).ConfigureAwait(false);
if (refused.Task.IsCompleted) throw new CultNetWriteRefusedException(await refused.Task.ConfigureAwait(false));
await window.ConfigureAwait(false);
}
}
}