using Akka.Actor; using Akka.TestKit.Xunit2; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances; using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites; using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories; using ZB.MOM.WW.ScadaBridge.Communication; using ZB.MOM.WW.ScadaBridge.Communication.Actors; using ZB.MOM.WW.ScadaBridge.Communication.Grpc; namespace ZB.MOM.WW.ScadaBridge.Communication.Tests; /// /// Tests for DebugStreamService session lifecycle. /// /// /// Shares the DebugStreamStatics xUnit collection with DebugStreamBridgeActorTests /// so the two classes never race on the actor's static test seams (see that class). /// [Collection("DebugStreamStatics")] public class DebugStreamServiceTests : TestKit { /// Verifies that a stream that terminates before the snapshot arrives throws a meaningful exception. /// A task that represents the asynchronous operation. [Fact] public async Task StartStreamAsync_StreamTerminatesBeforeSnapshot_ThrowsMeaningfulException() { // Regression test: when the debug stream terminates before // the initial snapshot arrives, StartStreamAsync used to let the raw // InvalidOperationException from onTerminatedWrapper escape its // OperationCanceledException-only catch — the caller saw an untranslated exception // and the failure path did not deterministically tear the bridge actor down. // The fix catches any failure, tells the bridge actor StopDebugStream, and throws // a descriptive exception that names the instance and wraps the underlying cause. var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 }; var site = new Site("Site One", "site-1") { Id = 3, GrpcNodeAAddress = "http://localhost:5100", GrpcNodeBAddress = "http://localhost:5200" }; var instanceRepo = Substitute.For(); instanceRepo.GetInstanceByIdAsync(7, Arg.Any()).Returns(instance); var siteRepo = Substitute.For(); siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); var services = new ServiceCollection(); services.AddScoped(_ => instanceRepo); services.AddScoped(_ => siteRepo); using var provider = services.BuildServiceProvider(); var commProbe = CreateTestProbe(); var commService = new CommunicationService( Options.Create(new CommunicationOptions()), NullLogger.Instance); commService.SetCommunicationActor(commProbe.Ref); using var grpcFactory = new SiteStreamGrpcClientFactory(NullLoggerFactory.Instance); var service = new DebugStreamService( commService, provider, grpcFactory, NullLogger.Instance); service.SetActorSystem(Sys); // Act — start the stream; it blocks awaiting the initial snapshot. var startTask = service.StartStreamAsync(instanceId: 7, onEvent: _ => { }, onTerminated: () => { }); // The bridge actor's PreStart sends SubscribeDebugViewRequest to the comm actor; // the envelope's sender is the bridge actor itself. commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); var bridgeActor = commProbe.LastSender; // Simulate the site terminating the stream before any snapshot is delivered. bridgeActor.Tell(new DebugStreamTerminated("site-1", "corr")); // Assert — a descriptive exception that names the instance and wraps the cause, // not the raw "terminated before snapshot received" InvalidOperationException. var ex = await Assert.ThrowsAsync(() => startTask); Assert.Contains("Site1.Pump01", ex.Message); Assert.NotNull(ex.InnerException); } /// Verifies that an attached session is kept alive by the service keepalive and dies once detached. /// A task that represents the asynchronous operation. [Fact] public async Task AttachedSession_IsKeptAliveByTheServiceKeepalive_AndDiesOnceDetached() { // The consumer half of the orphan net: holding a session in DebugStreamService IS // "a consumer is attached", and the service's shared timer is what renews the bridge // actor's window. Without this wiring every healthy session self-terminated one // window after its snapshot (the old mailbox-based ReceiveTimeout had nothing // recurring to reset it) and the consumer was told "Site disconnected". var previousKeepalive = DebugStreamService.KeepaliveInterval; var previousIdle = DebugStreamBridgeActor.ConsumerIdleTimeout; var previousCheck = DebugStreamBridgeActor.ConsumerLivenessCheckInterval; DebugStreamService.KeepaliveInterval = TimeSpan.FromMilliseconds(50); DebugStreamBridgeActor.ConsumerIdleTimeout = TimeSpan.FromMilliseconds(400); DebugStreamBridgeActor.ConsumerLivenessCheckInterval = TimeSpan.FromMilliseconds(50); try { var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 }; var site = new Site("Site One", "site-1") { Id = 3, GrpcNodeAAddress = "http://localhost:5100", GrpcNodeBAddress = "http://localhost:5200" }; var instanceRepo = Substitute.For(); instanceRepo.GetInstanceByIdAsync(7, Arg.Any()).Returns(instance); var siteRepo = Substitute.For(); siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); var services = new ServiceCollection(); services.AddScoped(_ => instanceRepo); services.AddScoped(_ => siteRepo); using var provider = services.BuildServiceProvider(); var commProbe = CreateTestProbe(); var commService = new CommunicationService( Options.Create(new CommunicationOptions()), NullLogger.Instance); commService.SetCommunicationActor(commProbe.Ref); // Mock gRPC factory: the real one would dial localhost:5100, fail, and trip the // bridge actor's retry budget — a termination unrelated to the orphan net under // test. The mock keeps the stream "up" so the only thing that can end this // session is the consumer-liveness decision. using var grpcFactory = new Grpc.MockSiteStreamGrpcClientFactory( new Grpc.MockSiteStreamGrpcClient()); using var service = new DebugStreamService( commService, provider, grpcFactory, NullLogger.Instance); service.SetActorSystem(Sys); var startTask = service.StartStreamAsync( instanceId: 7, onEvent: _ => { }, onTerminated: () => { }); commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); var bridgeActor = commProbe.LastSender; Watch(bridgeActor); // Resolve the snapshot so the session is fully established. bridgeActor.Tell(new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot( "Site1.Pump01", new List(), new List(), DateTimeOffset.UtcNow)); var session = await startTask; // Several orphan windows with NO traffic of any kind — only the service's // keepalive timer. The session must survive. await Task.Delay(TimeSpan.FromMilliseconds(1500)); ExpectNoMsg(TimeSpan.FromMilliseconds(100)); Assert.False(bridgeActor.IsNobody()); // Detach the consumer: the session leaves the registry, keepalives stop, and the // actor is stopped (StopStream) — the orphan net is the backstop for the case // where that explicit stop never happens. service.StopStream(session.SessionId); ExpectTerminated(bridgeActor, TimeSpan.FromSeconds(3)); } finally { DebugStreamService.KeepaliveInterval = previousKeepalive; DebugStreamBridgeActor.ConsumerIdleTimeout = previousIdle; DebugStreamBridgeActor.ConsumerLivenessCheckInterval = previousCheck; } } /// Verifies that an InstanceNotFound snapshot does not leave a registered session behind (review 2026-10-21 03/M-3). /// A task that represents the asynchronous operation. [Fact] public async Task StartStreamAsync_InstanceNotFoundSnapshot_DoesNotRegisterASession() { var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 }; var site = new Site("Site One", "site-1") { Id = 3, GrpcNodeAAddress = "http://localhost:5100", GrpcNodeBAddress = "http://localhost:5200" }; var instanceRepo = Substitute.For(); instanceRepo.GetInstanceByIdAsync(7, Arg.Any()).Returns(instance); var siteRepo = Substitute.For(); siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); var services = new ServiceCollection(); services.AddScoped(_ => instanceRepo); services.AddScoped(_ => siteRepo); using var provider = services.BuildServiceProvider(); var commProbe = CreateTestProbe(); var commService = new CommunicationService( Options.Create(new CommunicationOptions()), NullLogger.Instance); commService.SetCommunicationActor(commProbe.Ref); using var grpcFactory = new Grpc.MockSiteStreamGrpcClientFactory( new Grpc.MockSiteStreamGrpcClient()); using var service = new DebugStreamService( commService, provider, grpcFactory, NullLogger.Instance); service.SetActorSystem(Sys); var startTask = service.StartStreamAsync(instanceId: 7, onEvent: _ => { }, onTerminated: () => { }); commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); var bridgeActor = commProbe.LastSender; Watch(bridgeActor); bridgeActor.Tell(new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot( "Site1.Pump01", new List(), new List(), DateTimeOffset.UtcNow, InstanceNotFound: true)); var session = await startTask; // The caller still sees the flag, but the bridge actor has stopped itself — the // service must not keep a live-looking session for it (keepalives to a dead actor). Assert.True(session.InitialSnapshot.InstanceNotFound); Assert.Equal(0, service.SessionCount); ExpectTerminated(bridgeActor, TimeSpan.FromSeconds(3)); } // --- COMM-3 / COMM-7 --- private (DebugStreamService Service, Akka.TestKit.TestProbe CommProbe, ServiceProvider Provider, IDisposable Factory) NewMockedService() { var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 }; var site = new Site("Site One", "site-1") { Id = 3, GrpcNodeAAddress = "http://localhost:5100", GrpcNodeBAddress = "http://localhost:5200" }; var instanceRepo = Substitute.For(); instanceRepo.GetInstanceByIdAsync(7, Arg.Any()).Returns(instance); var siteRepo = Substitute.For(); siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); var services = new ServiceCollection(); services.AddScoped(_ => instanceRepo); services.AddScoped(_ => siteRepo); var provider = services.BuildServiceProvider(); var commProbe = CreateTestProbe(); var commService = new CommunicationService( Options.Create(new CommunicationOptions()), NullLogger.Instance); commService.SetCommunicationActor(commProbe.Ref); var grpcFactory = new Grpc.MockSiteStreamGrpcClientFactory(new Grpc.MockSiteStreamGrpcClient()); var service = new DebugStreamService( commService, provider, grpcFactory, NullLogger.Instance); service.SetActorSystem(Sys); return (service, commProbe, provider, grpcFactory); } private static ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AttributeValueChanged Attr( string name, object? value, DateTimeOffset ts) => new("Site1.Pump01", "", name, value, "Good", ts); /// /// COMM-3 regression: a gap-window event (captured while the snapshot was being built, newer /// than the snapshot row) must not reach the consumer ahead of the snapshot. It is folded into /// the snapshot StartStreamAsync returns, and only later events are delivered to onEvent. /// /// A task that represents the asynchronous operation. [Fact] public async Task Comm3_GapWindowEvent_IsFoldedIntoTheSnapshot_NotDeliveredAheadOfIt() { var (service, commProbe, provider, factory) = NewMockedService(); using var _p = provider; using var _f = factory; using var _s = service; var delivered = new System.Collections.Concurrent.ConcurrentQueue(); var t0 = DateTimeOffset.UtcNow; var startTask = service.StartStreamAsync(7, onEvent: e => delivered.Enqueue(e), onTerminated: () => { }); commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); var bridge = commProbe.LastSender; // Arrives on the stream BEFORE the snapshot (stream-first), but is newer than the row. bridge.Tell(Attr("Speed", 42.0, t0.AddSeconds(2))); bridge.Tell(new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot( "Site1.Pump01", new List { Attr("Speed", 10.0, t0.AddSeconds(1)) }, new List(), t0.AddSeconds(1))); var session = await startTask; var speed = Assert.Single(session.InitialSnapshot.AttributeValues); Assert.Equal(42.0, speed.Value); Assert.Empty(delivered); // After the hand-over, events pass straight through. bridge.Tell(Attr("Speed", 43.0, t0.AddSeconds(3))); AwaitCondition(() => !delivered.IsEmpty, TimeSpan.FromSeconds(3)); var live = Assert.IsType(Assert.Single(delivered)); Assert.Equal(43.0, live.Value); service.StopStream(session.SessionId); } /// COMM-3: the fold keeps a newer snapshot row over an older event and appends unseen entities. [Fact] public void Comm3_FoldIntoSnapshot_RespectsTimestamps_AndAppendsNewEntities() { var t0 = DateTimeOffset.UtcNow; var snapshot = new ZB.MOM.WW.ScadaBridge.Commons.Messages.DebugView.DebugViewSnapshot( "Site1.Pump01", new List { Attr("A", 1, t0.AddSeconds(5)) }, new List(), t0); var folded = DebugStreamService.FoldIntoSnapshot(snapshot, new object[] { Attr("A", 0, t0.AddSeconds(1)), // older than the row: ignored Attr("B", 2, t0.AddSeconds(2)), // not in the snapshot: appended new ZB.MOM.WW.ScadaBridge.Commons.Messages.Streaming.AlarmStateChanged( "Site1.Pump01", "Hi", ZB.MOM.WW.ScadaBridge.Commons.Types.Enums.AlarmState.Active, 500, t0.AddSeconds(3)), }); Assert.Equal(1, folded.AttributeValues.Single(a => a.AttributeName == "A").Value); Assert.Equal(2, folded.AttributeValues.Single(a => a.AttributeName == "B").Value); Assert.Single(folded.AlarmStates); } /// /// COMM-7 regression: the command transport's fail-fast Status.Failure reply to the /// snapshot request ends the start immediately with the real cause, instead of the 30 s /// timeout, and tears the bridge actor down. /// /// A task that represents the asynchronous operation. [Fact] public async Task Comm7_SnapshotRequestFailure_FailsStartFastWithTheCause() { var (service, commProbe, provider, factory) = NewMockedService(); using var _p = provider; using var _f = factory; using var _s = service; var terminated = false; var startTask = service.StartStreamAsync(7, onEvent: _ => { }, onTerminated: () => terminated = true); commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); var bridge = commProbe.LastSender; Watch(bridge); bridge.Tell(new Status.Failure(new InvalidOperationException("no gRPC channel for site site-1"))); var ex = await Assert.ThrowsAsync(() => startTask.WaitAsync(TimeSpan.FromSeconds(5))); Assert.Contains("no gRPC channel for site site-1", ex.Message); Assert.True(terminated); ExpectTerminated(bridge, TimeSpan.FromSeconds(3)); Assert.Equal(0, service.SessionCount); } // --- single-endpoint sites --- /// Verifies that a single-endpoint site uses its sole address for both node slots. /// The gRPC address of node A, or null. /// The gRPC address of node B, or null. /// A task that represents the asynchronous operation. [Theory] [InlineData("http://localhost:5100", null)] [InlineData(null, "http://localhost:5200")] public async Task StartStreamAsync_SingleEndpointSite_UsesTheSoleAddressForBothNodeSlots( string? nodeA, string? nodeB) { // Debug View used to hard-require BOTH gRPC node addresses and threw before ever // creating the bridge actor, though single-endpoint sites are supported everywhere else // (SiteAlarmLiveCacheService's N9 degeneration, SitePairChannelProvider's null-tolerant // pair). The sole configured address now fills both slots, so the bridge actor's // NodeA↔NodeB flip degenerates to a reconnect against the same node. var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 }; var site = new Site("Site One", "site-1") { Id = 3, GrpcNodeAAddress = nodeA, GrpcNodeBAddress = nodeB }; var instanceRepo = Substitute.For(); instanceRepo.GetInstanceByIdAsync(7, Arg.Any()).Returns(instance); var siteRepo = Substitute.For(); siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); var services = new ServiceCollection(); services.AddScoped(_ => instanceRepo); services.AddScoped(_ => siteRepo); using var provider = services.BuildServiceProvider(); var commProbe = CreateTestProbe(); var commService = new CommunicationService( Options.Create(new CommunicationOptions()), NullLogger.Instance); commService.SetCommunicationActor(commProbe.Ref); using var grpcFactory = new Grpc.MockSiteStreamGrpcClientFactory( new Grpc.MockSiteStreamGrpcClient()); using var service = new DebugStreamService( commService, provider, grpcFactory, NullLogger.Instance); service.SetActorSystem(Sys); // Act — resolution must get past the address check and start a bridge actor. var startTask = service.StartStreamAsync(instanceId: 7, onEvent: _ => { }, onTerminated: () => { }); commProbe.ExpectMsg(TimeSpan.FromSeconds(5)); var bridgeActor = commProbe.LastSender; // The stream it opened dials the ONE configured address. Assert.Equal(new[] { nodeA ?? nodeB }, grpcFactory.RequestedEndpoints); // Unwind the session. bridgeActor.Tell(new DebugStreamTerminated("site-1", "corr")); await Assert.ThrowsAsync(() => startTask); } /// Verifies that a site with no gRPC addresses still throws. /// A task that represents the asynchronous operation. [Fact] public async Task StartStreamAsync_SiteWithNoGrpcAddresses_StillThrows() { // Degenerating a single endpoint must not degenerate into accepting NONE. var instance = new Instance("Site1.Pump01") { Id = 7, SiteId = 3 }; var site = new Site("Site One", "site-1") { Id = 3 }; var instanceRepo = Substitute.For(); instanceRepo.GetInstanceByIdAsync(7, Arg.Any()).Returns(instance); var siteRepo = Substitute.For(); siteRepo.GetSiteByIdAsync(3, Arg.Any()).Returns(site); var services = new ServiceCollection(); services.AddScoped(_ => instanceRepo); services.AddScoped(_ => siteRepo); using var provider = services.BuildServiceProvider(); var commService = new CommunicationService( Options.Create(new CommunicationOptions()), NullLogger.Instance); commService.SetCommunicationActor(CreateTestProbe().Ref); using var grpcFactory = new SiteStreamGrpcClientFactory(NullLoggerFactory.Instance); using var service = new DebugStreamService( commService, provider, grpcFactory, NullLogger.Instance); service.SetActorSystem(Sys); var ex = await Assert.ThrowsAsync(() => service.StartStreamAsync(instanceId: 7, onEvent: _ => { }, onTerminated: () => { })); Assert.Contains("no gRPC node addresses", ex.Message); } }