Files
mxaccessgw/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayEventStream.cs
T
Joseph Doherty 31e16fbc80 fix(client-dotnet): keepalive, error mapping, lifecycle, CLI batch/redaction (CDN-001..011, #257)
- keepalive: 30 s ping / 10 s timeout / Always, configurable via KeepAlivePingDelay/Timeout (CDN-004, D7)
- GrpcStatusMapper shared by both transports: server Cancelled with a live token is no longer
  OperationCanceledException; NotFound/FailedPrecondition on session RPCs -> MxGatewaySessionException;
  MxGatewayException.GrpcStatusCode preserves the status (CDN-001, CDN-002)
- Register/AddItem/AddItem2 raise MxGatewayMalformedReplyException on a payload-less reply (CDN-008)
- MxGatewayEventStream.DisposeAsync waits for the in-flight read (CDN-003); session DisposeAsync
  is bounded to 5 s and swallows cancellation (CDN-005); owned handler + pinned CA disposed (CDN-006)
- ResourceExhausted no longer retried (CDN-007)
- CLI: batch reuses clients, stream/bench commands exempt from the 30 s timeout, OCE reported as
  an error with exit 1, --value redacted only for write-secured* and only as a whole token,
  bench backs off on failures (CDN-009, CDN-010, CDN-011)
2026-12-03 09:44:02 -05:00

193 lines
7.3 KiB
C#

using System.Runtime.CompilerServices;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Client;
/// <summary>
/// An event stream the gateway has confirmed attached (#227), returned by
/// <see cref="MxGatewaySession.OpenEventStreamAsync"/>. Its existence is the attach signal:
/// every event the session publishes after it was created reaches <see cref="ReadAllAsync"/>.
/// </summary>
/// <remarks>
/// 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 <see cref="MxEvent.ReplayGap"/>, or wrap with
/// <see cref="MxEventStreamExtensions.AsStreamItemsAsync"/>). Dispose to end the call.
/// </remarks>
public sealed class MxGatewayEventStream : IAsyncDisposable
{
private readonly IAsyncEnumerator<MxEvent> _enumerator;
private readonly CancellationTokenSource _lifetime;
// Held for the duration of each MoveNextAsync. An async iterator cannot be disposed while a
// MoveNext is in flight, so DisposeAsync takes the gate (after cancelling) to wait for the
// cancelled read to unwind before it disposes the enumerator (CDN-003).
private readonly SemaphoreSlim _readGate = new(1, 1);
private int _readStarted;
private int _disposed;
private MxGatewayEventStream(
IAsyncEnumerator<MxEvent> enumerator,
CancellationTokenSource lifetime,
StreamAttached attached)
{
_enumerator = enumerator;
_lifetime = lifetime;
Attached = attached;
}
/// <summary>
/// The gateway's attach acknowledgement. Live events on this stream have a
/// <c>worker_sequence</c> strictly greater than <see cref="StreamAttached.LiveAfterSequence"/>.
/// </summary>
public StreamAttached Attached { get; }
/// <summary>
/// Reads the events that follow the attach acknowledgement. May be enumerated once.
/// </summary>
/// <param name="cancellationToken">Cancels the enumeration and ends the stream.</param>
/// <returns>The remaining events, in gateway order.</returns>
/// <exception cref="InvalidOperationException">The stream was already enumerated.</exception>
public async IAsyncEnumerable<MxEvent> 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 (true)
{
MxEvent current;
await _readGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
if (Volatile.Read(ref _disposed) != 0)
{
throw new OperationCanceledException("The event stream was disposed.");
}
if (!await _enumerator.MoveNextAsync().ConfigureAwait(false))
{
yield break;
}
current = _enumerator.Current;
}
finally
{
_readGate.Release();
}
yield return current;
}
}
/// <summary>Cancels the underlying call and releases it.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public async ValueTask DisposeAsync()
{
if (Interlocked.Exchange(ref _disposed, 1) != 0)
{
return;
}
await _lifetime.CancelAsync().ConfigureAwait(false);
// Wait for an in-flight read (cancelled above) to unwind; its outcome belongs to the reader.
await _readGate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
await _enumerator.DisposeAsync().ConfigureAwait(false);
}
finally
{
_lifetime.Dispose();
_readGate.Release();
}
}
// 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<MxGatewayEventStream> OpenAsync(
Func<CancellationToken, IAsyncEnumerable<MxEvent>> openStream,
string sessionId,
TimeSpan? attachTimeout,
CancellationToken cancellationToken)
{
CancellationTokenSource lifetime = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
IAsyncEnumerator<MxEvent> enumerator = openStream(lifetime.Token).GetAsyncEnumerator(lifetime.Token);
Task<bool>? 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();
}
}
}
}
}