Files
mxaccessgw/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientWireTests.cs
T
Joseph Doherty afd504d5ae
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m28s
ci / java (push) Failing after 2m21s
ci / portable (push) Failing after 3m33s
feat(events): opt-in stream-attached acknowledgement on StreamEvents (#227)
A fresh StreamEvents is never replayed, so an initial value published before
the gateway registers the stream's subscriber is lost (lmxopcua#865 —
slow-changing ScanState). Clients had nothing deterministic to wait on.

Contract (additive, proto3):
- StreamEventsRequest.emit_stream_attached = 3 (bool, default false)
- MxEvent.stream_attached = 15 (optional StreamAttached)
- message StreamAttached { uint64 live_after_sequence = 1; }
- OpenSessionReply capability "stream-events-attached-ack"
  (GatewayCapabilities.StreamEventsAttachedAck)

When requested, EventStreamService yields the sentinel as the FIRST message,
after AttachEventSubscriber/AttachEventSubscriberWithReplay has returned, so
receipt implies registration; refused attaches never see it. It precedes the
ReplayGap sentinel and replay on a resume. Shape mirrors ReplayGap: family
UNSPECIFIED, no body, worker_sequence 0.

Opt-in rather than always-on: ScadaBridge's MxGateway adapter stores every
streamed event's worker_sequence as its resume cursor, so an unrequested
sentinel would reset it to 0. Default wire behaviour is unchanged.

.NET client: StreamEventsAsync/StreamEventItemsAsync(after, emitStreamAttached),
MxEventStreamItem.IsStreamAttached, MxGatewaySession.SupportsStreamAttachedAck,
and OpenEventStreamAsync -> MxGatewayEventStream (awaits the sentinel, with
attach timeout; refuses older gateways).

Regenerated Contracts/Generated, the client protoset, Go and Python bindings
(also picks up comment-only drift already on main), synced the Rust vendored
proto and set emit_stream_attached in the Rust StreamEventsRequest literals.
No package versions bumped.

Tests: ordering (sentinel first, then events), race proof (event fanned right
after the sentinel is delivered — mutation-checked: fails when the sentinel is
yielded before registration), resume-with-gap order, refused attach emits no
sentinel, default emits none, contract field numbers, capability, and .NET
client wire tests (await, no-capability, older gateway, timeout).
2026-11-12 07:27:17 -05:00

295 lines
13 KiB
C#

using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Client.Tests;
/// <summary>
/// Drives the public client API against <see cref="WireFakeGatewayServer"/> — a real
/// gRPC server on loopback — so the transport, protobuf serialization, call metadata,
/// and gRPC status mapping are all exercised. Every other test in this project
/// substitutes <see cref="FakeGatewayTransport"/> and therefore proves nothing about
/// what actually crosses the wire.
/// </summary>
public sealed class MxGatewayClientWireTests
{
private const string ApiKey = "mxgw_wiretest_secret";
/// <summary>
/// Verifies the full session happy path decodes real wire bytes end to end.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task SessionRoundTrip_OverRealTransport_DecodesEveryReplyField()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync();
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(
new OpenSessionRequest { ClientSessionName = "wire-test" });
Assert.Equal(WireFakeGatewayServer.FakeGatewayService.SessionId, session.SessionId);
Assert.Equal("fake-backend", session.OpenSessionReply.BackendName);
Assert.Equal(1234, session.OpenSessionReply.WorkerProcessId);
Assert.Equal(3u, session.OpenSessionReply.GatewayProtocolVersion);
Assert.Equal(["events", "invoke"], session.OpenSessionReply.Capabilities);
int serverHandle = await session.RegisterAsync("wire-test-client");
Assert.Equal(WireFakeGatewayServer.FakeGatewayService.ServerHandle, serverHandle);
MxCommandRequest? invoke = server.Service.InvokeRequest;
Assert.NotNull(invoke);
Assert.Equal(MxCommandKind.Register, invoke.Command.Kind);
Assert.Equal("wire-test-client", invoke.Command.Register.ClientName);
List<MxEvent> events = await CollectAsync(client.StreamEventsAsync(
new StreamEventsRequest { SessionId = session.SessionId }));
MxEvent single = Assert.Single(events);
Assert.Equal(MxEventFamily.OnDataChange, single.Family);
Assert.Equal(WireFakeGatewayServer.FakeGatewayService.ServerHandle, single.ServerHandle);
Assert.Equal(WireFakeGatewayServer.FakeGatewayService.ItemHandle, single.ItemHandle);
Assert.Equal(17, single.Value.Int32Value);
Assert.Equal(192, single.Quality);
Assert.Equal(9ul, single.WorkerSequence);
Assert.Equal(MxEvent.BodyOneofCase.OnDataChange, single.BodyCase);
CloseSessionReply closeReply = await session.CloseAsync();
Assert.Equal(SessionState.Closed, closeReply.FinalState);
Assert.Equal(
WireFakeGatewayServer.FakeGatewayService.SessionId,
server.Service.CloseSessionRequest?.SessionId);
}
/// <summary>
/// Verifies the API key reaches the server as a bearer header on unary and
/// streaming calls alike. A transport fake can only assert what the client passes;
/// this asserts what the server receives.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ApiKey_ReachesTheServerAsBearerMetadata_OnEveryRpc()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync();
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(
new OpenSessionRequest { ClientSessionName = "wire-test" });
await session.RegisterAsync("wire-test-client");
await CollectAsync(client.StreamEventsAsync(
new StreamEventsRequest { SessionId = session.SessionId }));
await session.CloseAsync();
string expected = $"Bearer {ApiKey}";
Assert.Equal(
new Dictionary<string, string>
{
["OpenSession"] = expected,
["Invoke"] = expected,
["StreamEvents"] = expected,
["CloseSession"] = expected,
},
server.Service.AuthorizationByMethod);
}
/// <summary>
/// Verifies the gateway's replay-gap sentinel survives serialization and is
/// surfaced as a typed, non-terminal stream item.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ReplayGapSentinel_SurvivesTheWire_AsTypedStreamItem()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(service =>
service.ReplayGap = new ReplayGap
{
RequestedAfterSequence = 3,
OldestAvailableSequence = 8,
});
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(
new OpenSessionRequest { ClientSessionName = "wire-test" });
List<MxEventStreamItem> items = [];
IAsyncEnumerable<MxEvent> stream = client.StreamEventsAsync(new StreamEventsRequest
{
SessionId = session.SessionId,
AfterWorkerSequence = 3,
});
await foreach (MxEventStreamItem item in stream.AsStreamItemsAsync())
{
items.Add(item);
}
Assert.Equal(2, items.Count);
Assert.True(items[0].IsReplayGap);
Assert.Equal(3ul, items[0].ReplayGap!.RequestedAfterSequence);
Assert.Equal(8ul, items[0].ReplayGap!.OldestAvailableSequence);
Assert.False(items[1].IsReplayGap);
Assert.Equal(MxEventFamily.OnDataChange, items[1].Event.Family);
Assert.Equal(3ul, server.Service.StreamEventsRequest?.AfterWorkerSequence);
}
/// <summary>
/// #227: <see cref="MxGatewaySession.OpenEventStreamAsync"/> asks for the attach
/// acknowledgement, completes on the sentinel, and yields only the events after it.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OpenEventStreamAsync_AwaitsTheAttachSentinel_ThenYieldsLaterEvents()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(service =>
service.SupportsStreamAttached = true);
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(new OpenSessionRequest());
Assert.True(session.SupportsStreamAttachedAck);
await using MxGatewayEventStream stream = await session.OpenEventStreamAsync(
attachTimeout: TimeSpan.FromSeconds(10));
Assert.True(server.Service.StreamEventsRequest?.EmitStreamAttached);
Assert.Equal(0ul, stream.Attached.LiveAfterSequence);
List<MxEvent> events = [];
await foreach (MxEvent gatewayEvent in stream.ReadAllAsync())
{
events.Add(gatewayEvent);
}
MxEvent only = Assert.Single(events);
Assert.Null(only.StreamAttached);
Assert.Equal(9ul, only.WorkerSequence);
}
/// <summary>
/// #227: a session whose gateway does not advertise the capability fails fast with
/// <see cref="NotSupportedException"/> and never opens a stream.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OpenEventStreamAsync_OnGatewayWithoutCapability_ThrowsWithoutStreaming()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync();
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(new OpenSessionRequest());
Assert.False(session.SupportsStreamAttachedAck);
await Assert.ThrowsAsync<NotSupportedException>(() => session.OpenEventStreamAsync());
Assert.Null(server.Service.StreamEventsRequest);
}
/// <summary>
/// #227: a session bound with AttachSession (no capability list) against an older gateway
/// sees a normal event first and is refused rather than handed an unacknowledged stream.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OpenEventStreamAsync_AttachedSessionOnOlderGateway_RejectsNonSentinelFirstMessage()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync();
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = client.AttachSession(WireFakeGatewayServer.FakeGatewayService.SessionId);
await Assert.ThrowsAsync<NotSupportedException>(
() => session.OpenEventStreamAsync(attachTimeout: TimeSpan.FromSeconds(10)));
Assert.True(server.Service.StreamEventsRequest?.EmitStreamAttached);
}
/// <summary>
/// #227: against a quiet older gateway nothing arrives; the attach timeout bounds the wait.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task OpenEventStreamAsync_WhenNoSentinelArrives_TimesOut()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(service =>
service.StallStream = true);
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = client.AttachSession(WireFakeGatewayServer.FakeGatewayService.SessionId);
await Assert.ThrowsAsync<TimeoutException>(
() => session.OpenEventStreamAsync(attachTimeout: TimeSpan.FromMilliseconds(200)));
}
/// <summary>
/// Verifies a genuine <c>PERMISSION_DENIED</c> status maps to the typed client
/// exception rather than a bare RpcException.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task PermissionDeniedStatus_MapsToAuthorizationException()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(
service => service.DenyInvoke = true);
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(
new OpenSessionRequest { ClientSessionName = "wire-test" });
await Assert.ThrowsAsync<MxGatewayAuthorizationException>(
() => session.RegisterAsync("wire-test-client"));
}
/// <summary>
/// A <c>RESOURCE_EXHAUSTED</c> status carrying the <c>mxgw-reason</c> trailer surfaces the
/// reason as a typed property, so overflow and limit rejections can be told apart.
/// </summary>
/// <param name="reason">The reason code the fake gateway attaches.</param>
/// <param name="overflow">Whether the client should classify it as an overflow.</param>
/// <param name="limit">Whether the client should classify it as a subscriber-limit rejection.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData("event-queue-overflow", true, false)]
[InlineData("subscriber-limit", false, true)]
public async Task ResourceExhaustedStatus_ExposesReasonFromTrailer(string reason, bool overflow, bool limit)
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(
service =>
{
service.ExhaustInvoke = true;
service.ExhaustedReason = reason;
});
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(
new OpenSessionRequest { ClientSessionName = "wire-test" });
MxGatewayResourceExhaustedException exception =
await Assert.ThrowsAsync<MxGatewayResourceExhaustedException>(
() => session.RegisterAsync("wire-test-client"));
Assert.Equal(reason, exception.Reason);
Assert.Equal(overflow, exception.IsOverflow);
Assert.Equal(limit, exception.IsSubscriberLimit);
Assert.IsAssignableFrom<MxGatewayException>(exception);
}
/// <summary>A <c>RESOURCE_EXHAUSTED</c> from an older gateway (no trailer) has a null reason.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ResourceExhaustedStatus_WithoutTrailer_HasNullReason()
{
await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(
service => service.ExhaustInvoke = true);
await using MxGatewayClient client = server.CreateClient(ApiKey);
MxGatewaySession session = await client.OpenSessionAsync(
new OpenSessionRequest { ClientSessionName = "wire-test" });
MxGatewayResourceExhaustedException exception =
await Assert.ThrowsAsync<MxGatewayResourceExhaustedException>(
() => session.RegisterAsync("wire-test-client"));
Assert.Null(exception.Reason);
}
private static async Task<List<MxEvent>> CollectAsync(IAsyncEnumerable<MxEvent> stream)
{
List<MxEvent> events = [];
await foreach (MxEvent gatewayEvent in stream)
{
events.Add(gatewayEvent);
}
return events;
}
}