using Microsoft.Extensions.Logging; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; using ZB.MOM.WW.Secrets.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; /// /// lmxopcua#904 live gate: an acknowledge of a picker-form native alarm (attributeRef = tag.Attr) issued by a /// freshly started driver BEFORE its alarm feed has delivered the first snapshot — the window a host restart opens /// when it restores the condition from LocalDb. The driver must wait for the snapshot and dial the /// provider-qualified reference it names, and Galaxy must record the ack. /// /// Raise the alarm with a supervisory write through a separate driver instance. /// Negative control: a fresh driver whose feed has named nothing dials the bare /// tag.Attr, and the gateway refuses it (the pre-#904 behaviour). /// A fresh driver with the production wait acks before its snapshot arrived: the ack /// dials Galaxy!<Area>.tag.Attr and Galaxy's acknowledged transition confirms it. /// Clear the alarm. /// /// /// Skip-gated: runs only when MXGW_ENDPOINT, GALAXY_MXGW_API_KEY and GALAXY_904_ALARM_REF (a /// Boolean alarm attribute on a TEST Galaxy, e.g. TestMachine_015.TestAlarm003) are set. It raises, acks and /// clears that alarm. The ack account is GALAXY_904_ACK_USER (default Administrator) with the /// password in GALAXY_904_ACK_PASSWORD (default empty — the windev rig's identity). /// /// [Trait("Category", "Integration")] public sealed class GalaxyPickerAckBeforeSnapshotLiveTests { private const string RawPath = "g904/dev/alarm"; [Fact] public async Task Live_picker_form_ack_before_the_feed_snapshot_dials_the_provider_reference_and_reaches_galaxy() { var endpoint = Environment.GetEnvironmentVariable("MXGW_ENDPOINT"); var alarmRef = Environment.GetEnvironmentVariable("GALAXY_904_ALARM_REF"); if (string.IsNullOrWhiteSpace(endpoint) || string.IsNullOrWhiteSpace(alarmRef) || string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("GALAXY_MXGW_API_KEY"))) Assert.Skip("Set MXGW_ENDPOINT + GALAXY_MXGW_API_KEY + GALAXY_904_ALARM_REF to run the #904 live gate."); alarmRef.ShouldNotContain("!", customMessage: "the gate needs the picker form tag.Attr"); var ct = TestContext.Current.CancellationToken; await using var raiser = NewDriver("g904-raise", endpoint!, alarmRef!, out _); await raiser.InitializeAsync("{}", ct); try { // 1. Raise, and wait until the gateway feed reports it active + unacked. await WriteAsync(raiser, true, ct); var raised = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); raiser.OnAlarmEvent += (_, e) => { if (e.ConditionId == RawPath && e.Kind is AlarmTransitionKind.Raise or AlarmTransitionKind.Retrigger) raised.TrySetResult(raiser.ToAlarmAckReference(RawPath)); }; await raiser.SubscribeAlarmsAsync([RawPath], ct); var fullRef = await TestWait.ForAsync(raised.Task, "the gateway feed must report the raised alarm"); fullRef.ShouldStartWith("Galaxy!"); fullRef.ShouldEndWith("." + alarmRef); TestContext.Current.SendDiagnosticMessage($"#904 live: feed names the alarm {fullRef}"); // 2. Negative control — the pre-#904 state, deterministically: a fresh driver whose feed has named nothing // (not started, so nothing to wait for) dials the bare tag.Attr, and the gateway refuses it. await using (var control = NewDriver("g904-control", endpoint!, alarmRef!, out var controlLog)) { await control.InitializeAsync("{}", ct); control.ToAlarmAckReference(RawPath).ShouldBe(alarmRef); Exception? refused = null; try { await control.AcknowledgeAsync( [new AlarmAcknowledgeRequest(RawPath, RawPath, "#904 control (must be refused)")], ct); } catch (Exception ex) { refused = ex; } string text; lock (controlLog.Entries) text = controlLog.AllText; refused.ShouldNotBeNull($"the gateway must refuse the bare reference; log=\n{text}"); TestContext.Current.SendDiagnosticMessage($"#904 live control: {refused.GetType().Name}: {refused.Message}"); text.ShouldContain($"acknowledging {alarmRef} as Galaxy user", customMessage: text); } // 3. The fix — production wait: ack before the snapshot, dial the provider reference, Galaxy confirms. await using (var restarted = NewDriver("g904-restarted", endpoint!, alarmRef!, out var log)) { restarted.AckSnapshotWait.ShouldBe(TimeSpan.FromSeconds(2), "exercise the production wait"); await restarted.InitializeAsync("{}", ct); await restarted.SubscribeAlarmsAsync([RawPath], ct); var snapshot = restarted.AlarmFeedInitialSnapshotForTests!; snapshot.IsCompleted.ShouldBeFalse("the ack must be issued before the feed snapshot arrived"); restarted.ToAlarmAckReference(RawPath).ShouldBe(alarmRef, "nothing learned yet — the ack must have to wait"); AlarmAcknowledgeRequest[] request = [new AlarmAcknowledgeRequest(RawPath, RawPath, "OtOpcUa #904 live gate")]; await restarted.AcknowledgeAsync(request, ct); await restarted.ConfirmAcknowledgedAsync(request, ct); snapshot.IsCompletedSuccessfully.ShouldBeTrue(); lock (log.Entries) { log.AllText.ShouldContain($"acknowledging {fullRef} as Galaxy user", customMessage: log.AllText); log.AllText.ShouldNotContain("dials the area-free", customMessage: log.AllText); } TestContext.Current.SendDiagnosticMessage($"#904 live: ack before snapshot dialled {fullRef} and was confirmed"); } } finally { await WriteAsync(raiser, false, CancellationToken.None); } } private static async Task WriteAsync(GalaxyDriver driver, bool value, CancellationToken ct) { var results = await driver.WriteAsync([new WriteRequest(RawPath, value)], ct); results.ShouldHaveSingleItem().StatusCode.ShouldBe(StatusCodeMap.Good, $"write {value}"); } private static GalaxyDriver NewDriver(string id, string endpoint, string alarmRef, out CapturingLogger log) { log = new CapturingLogger(); var opts = new GalaxyDriverOptions( new GalaxyGatewayOptions(endpoint, "env:GALAXY_MXGW_API_KEY", UseTls: false), new GalaxyMxAccessOptions("OtOpcUa904-" + id), new GalaxyRepositoryOptions(WatchDeployEvents: false), new GalaxyReconnectOptions()) { RawTags = [new RawTagEntry(RawPath, $"{{\"attributeRef\":\"{alarmRef}\"}}", false)], AlarmAck = new GalaxyAlarmAckOptions( FallbackUser: Environment.GetEnvironmentVariable("GALAXY_904_ACK_USER") is { Length: > 0 } u ? u : "Administrator", FallbackPasswordSecretRef: Environment.GetEnvironmentVariable("GALAXY_904_ACK_PASSWORD") is { Length: > 0 } ? "env:GALAXY_904_ACK_PASSWORD" : "dev:"), }; return new GalaxyDriver(id, opts, new NullResolver(), new TypedLogger(log)); } private sealed class NullResolver : ISecretResolver { public Task GetAsync(SecretName name, CancellationToken ct) => Task.FromResult(null); } private sealed class TypedLogger(CapturingLogger inner) : ILogger { public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { lock (inner.Entries) inner.Log(logLevel, eventId, state, exception, formatter); } } }