using System.Runtime.CompilerServices;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Client;
///
/// An event stream the gateway has confirmed attached (#227), returned by
/// . Its existence is the attach signal:
/// every event the session publishes after it was created reaches .
///
///
/// The stream-attached sentinel is consumed when the stream opens and is not yielded again.
/// A replay-gap sentinel on a resumed stream is a normal stream item and is yielded as-is
/// (inspect , or wrap with
/// ). Dispose to end the call.
///
public sealed class MxGatewayEventStream : IAsyncDisposable
{
private readonly IAsyncEnumerator _enumerator;
private readonly CancellationTokenSource _lifetime;
private int _readStarted;
private int _disposed;
private MxGatewayEventStream(
IAsyncEnumerator enumerator,
CancellationTokenSource lifetime,
StreamAttached attached)
{
_enumerator = enumerator;
_lifetime = lifetime;
Attached = attached;
}
///
/// The gateway's attach acknowledgement. Live events on this stream have a
/// worker_sequence strictly greater than .
///
public StreamAttached Attached { get; }
///
/// Reads the events that follow the attach acknowledgement. May be enumerated once.
///
/// Cancels the enumeration and ends the stream.
/// The remaining events, in gateway order.
/// The stream was already enumerated.
public async IAsyncEnumerable ReadAllAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposed) != 0, this);
if (Interlocked.Exchange(ref _readStarted, 1) != 0)
{
throw new InvalidOperationException("The event stream can be enumerated only once.");
}
using CancellationTokenRegistration registration = cancellationToken.Register(
static state => ((CancellationTokenSource)state!).Cancel(),
_lifetime);
while (await _enumerator.MoveNextAsync().ConfigureAwait(false))
{
yield return _enumerator.Current;
}
}
/// Cancels the underlying call and releases it.
/// A task that represents the asynchronous operation.
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
await _lifetime.CancelAsync().ConfigureAwait(false);
try
{
await _enumerator.DisposeAsync().ConfigureAwait(false);
}
finally
{
_lifetime.Dispose();
}
}
// Opens the stream and consumes the first message, which must be the stream-attached
// sentinel. Anything else means the gateway ignored the request (it predates #227): the
// stream is closed rather than handed out, because it cannot keep the attach promise.
internal static async Task OpenAsync(
Func> openStream,
string sessionId,
TimeSpan? attachTimeout,
CancellationToken cancellationToken)
{
CancellationTokenSource lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
IAsyncEnumerator enumerator = openStream(lifetime.Token).GetAsyncEnumerator(lifetime.Token);
Task? first = null;
bool handedOff = false;
try
{
first = enumerator.MoveNextAsync().AsTask();
bool hasFirst;
try
{
hasFirst = attachTimeout is { } timeout
? await first.WaitAsync(timeout, cancellationToken).ConfigureAwait(false)
: await first.WaitAsync(cancellationToken).ConfigureAwait(false);
}
catch (TimeoutException) when (!first.IsCompleted)
{
throw new TimeoutException(
$"The gateway did not acknowledge the event-stream attach for session {sessionId} within {attachTimeout}.");
}
if (!hasFirst)
{
throw new MxGatewayException(
$"The gateway ended the event stream for session {sessionId} before acknowledging the attach.");
}
if (enumerator.Current.StreamAttached is not { } attached)
{
throw new NotSupportedException(
$"The gateway's first event-stream message for session {sessionId} was not the attach "
+ "acknowledgement; the gateway does not support emit_stream_attached.");
}
MxGatewayEventStream stream = new(enumerator, lifetime, attached);
handedOff = true;
return stream;
}
finally
{
if (!handedOff)
{
await lifetime.CancelAsync().ConfigureAwait(false);
// An async iterator cannot be disposed while a MoveNext is in flight (the timeout
// and caller-cancel paths leave one pending), so let the cancelled read unwind first.
// Its outcome is irrelevant: the failure being thrown is what the caller needs.
if (first is not null)
{
try
{
await first.ConfigureAwait(false);
}
catch (Exception)
{
// Swallowed deliberately; see above.
}
}
try
{
await enumerator.DisposeAsync().ConfigureAwait(false);
}
finally
{
lifetime.Dispose();
}
}
}
}
}