4c8539b897
The feed raises a new IGalaxyAlarmFeed.StreamOpened (default no-op accessors) before each stream's first message; GalaxyDriver records the live subscription then, and its sentinel signals only if that is still the live one — so refs whose snapshot entries arrived before (or without) the subscription are never signalled. The handle is now added before the feed starts, so the first stream opens under it.
239 lines
11 KiB
C#
239 lines
11 KiB
C#
using System.Threading.Channels;
|
|
using Google.Protobuf.WellKnownTypes;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
|
|
|
/// <summary>
|
|
/// grpc-data A1 (§5.1 Galaxy row): <see cref="GalaxyDriver"/> raises
|
|
/// <see cref="IAlarmInitialStateSignal.InitialAlarmStateDelivered"/> on <b>every</b> <c>snapshot_complete</c>
|
|
/// sentinel of the REAL <see cref="GatewayGalaxyAlarmFeed"/>, on the feed thread, after the snapshot entries were
|
|
/// bridged to <see cref="IAlarmSource.OnAlarmEvent"/>, covering the live subscription's refs; never while no alarm
|
|
/// subscription is live (G5); and again on a reopened stream's sentinel, so a condition a deploy added is covered
|
|
/// by the next one (vii).
|
|
/// </summary>
|
|
[Trait("Feature", "GrpcData")]
|
|
[Trait("Phase", "A1")]
|
|
public sealed class GalaxyInitialAlarmStateSignalTests
|
|
{
|
|
private const string Tank1 = "Tank01.Level.HiHi";
|
|
private const string Tank2 = "Tank02.Level.HiHi";
|
|
|
|
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
|
|
|
/// <summary>(ii) the replay's events precede the signal on the same ordered path; the signal lists the refs.</summary>
|
|
[Fact]
|
|
public async Task Sentinel_signals_after_the_snapshot_entries_covering_the_subscribed_refs()
|
|
{
|
|
await using var streams = new ScriptedStreams();
|
|
using var driver = NewDriver(streams.Feed);
|
|
var trace = Record(driver);
|
|
|
|
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
|
var s = await streams.NextAsync();
|
|
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
|
|
await s.WriteAsync(Snapshot(Tank2, AlarmConditionState.Inactive), Ct);
|
|
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
|
|
await TestWait.UntilAsync(() => trace.Count == 3, "two snapshot events then the signal", () => Dump(trace));
|
|
trace.ShouldBe(["event:" + Tank1, "event:" + Tank2, $"signal:{Tank1},{Tank2}"]);
|
|
}
|
|
|
|
/// <summary>Negative control: snapshot entries without their sentinel raise no signal.</summary>
|
|
[Fact]
|
|
public async Task No_signal_before_the_sentinel()
|
|
{
|
|
await using var streams = new ScriptedStreams();
|
|
using var driver = NewDriver(streams.Feed);
|
|
var trace = Record(driver);
|
|
|
|
await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
|
var s = await streams.NextAsync();
|
|
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
|
|
await TestWait.UntilAsync(() => trace.Count == 1, "the snapshot event", () => Dump(trace));
|
|
await Task.Delay(150, Ct);
|
|
trace.ShouldBe(["event:" + Tank1]);
|
|
}
|
|
|
|
/// <summary>(xi) G5: a sentinel that completes while no alarm subscription is live raises nothing.</summary>
|
|
[Fact]
|
|
public async Task Sentinel_while_unsubscribed_raises_nothing()
|
|
{
|
|
await using var streams = new ScriptedStreams();
|
|
using var driver = NewDriver(streams.Feed);
|
|
var trace = Record(driver);
|
|
|
|
var handle = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
|
var s = await streams.NextAsync();
|
|
// Registered AFTER the driver's own handler (wired by the subscribe), so it runs once the driver handled it.
|
|
var unsubscribedSentinel = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
streams.Feed.SnapshotDelivered += (_, _) => unsubscribedSentinel.TrySetResult();
|
|
await driver.UnsubscribeAlarmsAsync(handle, Ct);
|
|
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
|
|
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
await unsubscribedSentinel.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
|
// Positive control on the same stream: a live re-subscribe + the next reopen's sentinel DOES signal.
|
|
await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
|
s.Complete(new InvalidOperationException("reopen"));
|
|
var s2 = await streams.NextAsync();
|
|
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
|
|
await TestWait.UntilAsync(() => trace.Count >= 1, "the post-resubscribe signal", () => Dump(trace));
|
|
await Task.Delay(100, Ct);
|
|
trace.ShouldBe(["signal:" + Tank1]);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Review round 2 F4: a stream whose snapshot entries arrived while no subscription was live (they were dropped)
|
|
/// must not signal at its sentinel just because a subscription is live by then — the signal would cover refs whose
|
|
/// state never reached the host. The next stream, opened under the live subscription, signals.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_sentinel_for_a_stream_opened_under_an_earlier_subscription_does_not_signal()
|
|
{
|
|
await using var streams = new ScriptedStreams();
|
|
using var driver = NewDriver(streams.Feed);
|
|
var trace = Record(driver);
|
|
|
|
var first = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
|
var s = await streams.NextAsync();
|
|
await driver.UnsubscribeAlarmsAsync(first, Ct);
|
|
var sentinelSeen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
var entryHandled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
streams.Feed.OnAlarmTransition += (_, _) => entryHandled.TrySetResult();
|
|
await s.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct); // dropped: nothing is subscribed
|
|
await entryHandled.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
|
await driver.SubscribeAlarmsAsync([Tank1], Ct); // live again BEFORE the sentinel
|
|
streams.Feed.SnapshotDelivered += (_, _) => sentinelSeen.TrySetResult();
|
|
await s.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
await sentinelSeen.Task.WaitAsync(TimeSpan.FromSeconds(10), Ct);
|
|
trace.ShouldBeEmpty();
|
|
|
|
// Positive control: the next stream opens under the live subscription and its sentinel signals.
|
|
s.Complete(new InvalidOperationException("reopen"));
|
|
var s2 = await streams.NextAsync();
|
|
await s2.WriteAsync(Snapshot(Tank1, AlarmConditionState.Active), Ct);
|
|
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
await TestWait.UntilAsync(() => trace.Count >= 2, "the reopened stream's event and signal", () => Dump(trace));
|
|
trace.ShouldBe(["event:" + Tank1, "signal:" + Tank1]);
|
|
}
|
|
|
|
/// <summary>
|
|
/// (vii) a stream reopen re-signals; a deploy that adds a condition (re-subscribe with the larger set) is
|
|
/// covered by the NEXT sentinel, not before it.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Reopened_stream_signals_again_and_covers_a_condition_a_deploy_added()
|
|
{
|
|
await using var streams = new ScriptedStreams();
|
|
using var driver = NewDriver(streams.Feed);
|
|
var trace = Record(driver);
|
|
|
|
var h1 = await driver.SubscribeAlarmsAsync([Tank1], Ct);
|
|
var s1 = await streams.NextAsync();
|
|
await s1.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
await TestWait.UntilAsync(() => trace.Count == 1, "first sentinel", () => Dump(trace));
|
|
|
|
s1.Complete(new InvalidOperationException("gateway stream fault"));
|
|
var s2 = await streams.NextAsync();
|
|
await s2.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
await TestWait.UntilAsync(() => trace.Count == 2, "reopened stream's sentinel", () => Dump(trace));
|
|
|
|
// Deploy adds Tank2: DriverInstanceActor releases the old handle and subscribes the larger set.
|
|
await driver.UnsubscribeAlarmsAsync(h1, Ct);
|
|
await driver.SubscribeAlarmsAsync([Tank1, Tank2], Ct);
|
|
await Task.Delay(100, Ct);
|
|
trace.Count.ShouldBe(2, "a subscribe alone is not a signal — the active-alarm set was not re-read");
|
|
|
|
s2.Complete(new InvalidOperationException("gateway stream fault"));
|
|
var s3 = await streams.NextAsync();
|
|
await s3.WriteAsync(Snapshot(Tank2, AlarmConditionState.Active), Ct);
|
|
await s3.WriteAsync(new AlarmFeedMessage { SnapshotComplete = true }, Ct);
|
|
await TestWait.UntilAsync(() => trace.Count == 4, "the next sentinel", () => Dump(trace));
|
|
trace.ShouldBe(["signal:" + Tank1, "signal:" + Tank1, "event:" + Tank2, $"signal:{Tank1},{Tank2}"]);
|
|
}
|
|
|
|
private static List<string> Record(GalaxyDriver driver)
|
|
{
|
|
var trace = new List<string>();
|
|
driver.OnAlarmEvent += (_, e) => { lock (trace) trace.Add("event:" + e.ConditionId); };
|
|
driver.InitialAlarmStateDelivered += (_, e) =>
|
|
{
|
|
lock (trace) trace.Add("signal:" + string.Join(',', e.ConditionIds));
|
|
};
|
|
return trace;
|
|
}
|
|
|
|
private static string Dump(List<string> trace)
|
|
{
|
|
lock (trace) return string.Join(" | ", trace);
|
|
}
|
|
|
|
private static AlarmFeedMessage Snapshot(string reference, AlarmConditionState state) => new()
|
|
{
|
|
ActiveAlarm = new ActiveAlarmSnapshot
|
|
{
|
|
AlarmFullReference = reference,
|
|
SourceObjectReference = reference.Split('.')[0],
|
|
AlarmTypeName = "AnalogLimitAlarm.HiHi",
|
|
Severity = 750,
|
|
CurrentState = state,
|
|
Category = "Process",
|
|
Description = "Tank high-high level",
|
|
LastTransitionTimestamp = Timestamp.FromDateTime(DateTime.UtcNow),
|
|
},
|
|
};
|
|
|
|
private static GalaxyDriver NewDriver(IGalaxyAlarmFeed feed)
|
|
{
|
|
var options = new GalaxyDriverOptions(
|
|
new GalaxyGatewayOptions("http://localhost:5000", "literal-api-key"),
|
|
new GalaxyMxAccessOptions("SignalTest"),
|
|
new GalaxyRepositoryOptions(),
|
|
new GalaxyReconnectOptions());
|
|
return new GalaxyDriver(
|
|
driverInstanceId: "drv-1",
|
|
options: options,
|
|
hierarchySource: null,
|
|
alarmAcknowledger: null,
|
|
alarmFeed: feed,
|
|
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
|
}
|
|
|
|
/// <summary>A real feed over test-written streams; each (re)open takes the next channel.</summary>
|
|
private sealed class ScriptedStreams : IAsyncDisposable
|
|
{
|
|
private readonly Channel<Channel<AlarmFeedMessage>> _opened = Channel.CreateUnbounded<Channel<AlarmFeedMessage>>();
|
|
|
|
public ScriptedStreams()
|
|
{
|
|
Feed = new GatewayGalaxyAlarmFeed((_, ct) =>
|
|
{
|
|
var c = Channel.CreateUnbounded<AlarmFeedMessage>();
|
|
_opened.Writer.TryWrite(c);
|
|
return c.Reader.ReadAllAsync(ct);
|
|
}, clientName: "SignalTest", reconnectDelay: TimeSpan.FromMilliseconds(10));
|
|
}
|
|
|
|
public GatewayGalaxyAlarmFeed Feed { get; }
|
|
|
|
public async Task<ChannelWriter<AlarmFeedMessage>> NextAsync()
|
|
{
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
|
return (await _opened.Reader.ReadAsync(cts.Token)).Writer;
|
|
}
|
|
|
|
public ValueTask DisposeAsync() => Feed.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
file static class ChannelWriterExtensions
|
|
{
|
|
public static void Complete(this ChannelWriter<AlarmFeedMessage> writer, Exception ex) => writer.TryComplete(ex);
|
|
}
|