c9640f5ced
v2-ci / unit-tests (push) Has been cancelled
A picker-form native alarm (attributeRef tag.Attr) only learns the provider-qualified reference Galaxy!<Area>.tag.Attr from the alarm feed. After a host restart the condition can be restored from LocalDb before the feed's first snapshot reached the new driver, and an ack in that window dialled the bare tag.Attr, which the gateway's AcknowledgeAlarm refuses. The feed now exposes InitialSnapshotCompleted (set on snapshot_complete, after every snapshot entry has been raised). AcknowledgeAsync resolves the reference through ResolveAlarmAckReferenceAsync: when a picker-form tag has learned nothing yet and the feed is running, it waits for that snapshot (2 s, and the caller's token) and dials the reference the snapshot names, so the area always comes from the feed and a re-areaed object acks under its current area. No reference is guessed: if the snapshot does not name the alarm, or does not arrive in time, the authored reference is dialled as before and refused visibly. Chosen over the alternatives in the issue: a GR-browse area lookup can be stale against the runtime area and is not loaded for authored tags, and a gateway-side tag.Attr resolution needs a cross-repo deploy and would resolve from the same monitor cache the snapshot already carries. Tests: 5 driver cases + 1 feed case (fail with the call site / sentinel reverted), and a skip-gated live gate GalaxyPickerAckBeforeSnapshotLiveTests, run against windev's TEST Galaxy (TestMachine_015.TestAlarm003): an ack issued before the snapshot dials Galaxy!TestArea.TestMachine_015.TestAlarm003 and is confirmed; with the call site reverted it fails with the gateway's InvalidRequest refusal. Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
617 lines
30 KiB
C#
617 lines
30 KiB
C#
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
|
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>
|
|
/// v3 RawPath identity: the server addresses Galaxy nodes by RawPath, while MXAccess dials the
|
|
/// Galaxy attributeRef (<c>tag_name.AttributeName</c>). These tests pin the driver-side boundary
|
|
/// translation built from <see cref="GalaxyDriverOptions.RawTags"/> — RawPath → attributeRef on
|
|
/// read / write / subscribe / ack (forward dial), and attributeRef → RawPath on the value fan-out
|
|
/// and alarm ConditionId (reverse), so the alarm resolves back to the same RawPath the value path
|
|
/// surfaces. Each entry's <c>TagConfig</c> carries the dialled address under the camelCase key
|
|
/// <c>attributeRef</c>.
|
|
/// </summary>
|
|
public sealed class GalaxyDriverRawPathKeyingTests
|
|
{
|
|
private const string RawPath = "area/line/tank1/level";
|
|
private const string AttributeRef = "Tank1.Level";
|
|
|
|
private static GalaxyDriverOptions OptsWithRawTags(bool writeIdempotent = false) => new(
|
|
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
|
|
new GalaxyMxAccessOptions("OtOpcUa-A"),
|
|
new GalaxyRepositoryOptions(),
|
|
new GalaxyReconnectOptions())
|
|
{
|
|
RawTags = [new RawTagEntry(RawPath, $"{{\"attributeRef\":\"{AttributeRef}\"}}", writeIdempotent)],
|
|
};
|
|
|
|
// ===== Read: RawPath in → attributeRef dialled =====
|
|
|
|
/// <summary>ReadAsync translates the incoming RawPath to the Galaxy attributeRef before dialling.</summary>
|
|
[Fact]
|
|
public async Task ReadAsync_TranslatesRawPath_ToAttributeRef()
|
|
{
|
|
var reader = new RecordingReader();
|
|
using var driver = new GalaxyDriver("g", OptsWithRawTags(), hierarchySource: null, dataReader: reader);
|
|
|
|
await driver.ReadAsync([RawPath], CancellationToken.None);
|
|
|
|
reader.LastRequest.ShouldBe([AttributeRef]);
|
|
}
|
|
|
|
/// <summary>An unmapped RawPath dials as-is (identity) — the gateway then rejects an unknown address.</summary>
|
|
[Fact]
|
|
public async Task ReadAsync_UnmappedRawPath_DialsIdentity()
|
|
{
|
|
var reader = new RecordingReader();
|
|
using var driver = new GalaxyDriver("g", OptsWithRawTags(), hierarchySource: null, dataReader: reader);
|
|
|
|
await driver.ReadAsync(["not/authored"], CancellationToken.None);
|
|
|
|
reader.LastRequest.ShouldBe(["not/authored"]);
|
|
}
|
|
|
|
// ===== Write: RawPath in → attributeRef dialled, security resolved by RawPath =====
|
|
|
|
/// <summary>
|
|
/// WriteAsync dials the attributeRef, and the security the writer resolves is the one captured at
|
|
/// discovery under the tag's RawPath (the discoverer emitted FullName = RawPath) — proving the
|
|
/// reverse mapping the resolver applies (attributeRef → RawPath) lands on the right classification.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task WriteAsync_DialsAttributeRef_AndResolvesSecurityByRawPath()
|
|
{
|
|
var writer = new RecordingWriter();
|
|
// Hierarchy: Tank1.Level classified Operate (sec 1). Discovery keys security by the RawPath.
|
|
var src = new FakeHierarchySource([Obj("Tank1", Attr("Level", sec: 1))]);
|
|
using var driver = new GalaxyDriver(
|
|
"g", OptsWithRawTags(), hierarchySource: src, dataReader: null, dataWriter: writer);
|
|
|
|
await driver.DiscoverAsync(new CapturingBuilder(), CancellationToken.None);
|
|
await driver.WriteAsync([new WriteRequest(RawPath, 42.0)], CancellationToken.None);
|
|
|
|
writer.Calls.ShouldHaveSingleItem();
|
|
writer.Calls[0].FullRef.ShouldBe(AttributeRef); // dialled address
|
|
writer.Calls[0].Resolved.ShouldBe(SecurityClassification.Operate); // resolved by RawPath
|
|
}
|
|
|
|
// ===== Subscribe + value fan-out: RawPath in → attributeRef dialled → RawPath out =====
|
|
|
|
/// <summary>
|
|
/// SubscribeAsync dials the attributeRef; the resulting value fan-out surfaces on the public
|
|
/// OnDataChange keyed by the tag's RawPath — the same identity the alarm ConditionId uses.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Subscribe_DialsAttributeRef_AndValueFanOutSurfacesRawPath()
|
|
{
|
|
var subscriber = new GalaxyDriverSubscribeTests.FakeSubscriber();
|
|
using var driver = new GalaxyDriver(
|
|
"g", OptsWithRawTags(), hierarchySource: null, dataReader: null, dataWriter: null, subscriber: subscriber);
|
|
|
|
var captured = new List<DataChangeEventArgs>();
|
|
driver.OnDataChange += (_, args) => { lock (captured) captured.Add(args); };
|
|
|
|
await driver.SubscribeAsync([RawPath], TimeSpan.FromSeconds(1), CancellationToken.None);
|
|
|
|
// The gateway saw the dialled attributeRef, not the RawPath.
|
|
subscriber.Map.ShouldContainKey(AttributeRef);
|
|
subscriber.Map.ShouldNotContainKey(RawPath);
|
|
|
|
await subscriber.EmitOnDataChangeAsync(subscriber.Map[AttributeRef], 42.0);
|
|
await GalaxyDriverSubscribeTests.WaitForCapturedAsync(captured, 1, "the value change must be dispatched");
|
|
|
|
captured.ShouldHaveSingleItem();
|
|
captured[0].FullReference.ShouldBe(RawPath); // surfaced under the RawPath identity
|
|
((double)captured[0].Snapshot.Value!).ShouldBe(42.0);
|
|
}
|
|
|
|
// ===== Alarm: ConditionId is the RawPath; ack round-trips back to the attributeRef =====
|
|
|
|
/// <summary>
|
|
/// The alarm feed reports the Galaxy attributeRef; the driver surfaces the transition with
|
|
/// ConditionId = the tag's RawPath (matching the value path), and a subsequent ack keyed by that
|
|
/// RawPath dials back down to the attributeRef the gateway acknowledges.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Alarm_ConditionIdIsRawPath_AndAckRoundTripsToAttributeRef()
|
|
{
|
|
var feed = new FakeAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
using var driver = new GalaxyDriver(
|
|
"g", OptsWithRawTags(), hierarchySource: null, alarmAcknowledger: ack, alarmFeed: feed,
|
|
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
|
|
|
var handle = await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
var observed = new List<AlarmEventArgs>();
|
|
driver.OnAlarmEvent += (_, args) => observed.Add(args);
|
|
|
|
// Feed reports the dialled attributeRef.
|
|
feed.Emit(NewTransition(AttributeRef, "Tank1"));
|
|
|
|
observed.ShouldHaveSingleItem();
|
|
observed[0].ConditionId.ShouldBe(RawPath); // reverse-mapped to the RawPath identity
|
|
observed[0].SubscriptionHandle.ShouldBe(handle);
|
|
|
|
// Ack keyed by the RawPath the driver reported → dials back to the attributeRef.
|
|
await driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
|
|
ack.Calls.ShouldHaveSingleItem();
|
|
ack.Calls[0].AlarmRef.ShouldBe(AttributeRef);
|
|
}
|
|
|
|
/// <summary>
|
|
/// lmxopcua#895 (G6 live gate, windev 2026-11-12): the real gateway feed names an alarm
|
|
/// <c>Galaxy!Area.tag.Attr</c> with <c>SourceObjectReference = tag.Attr</c>, while the AdminUI Galaxy
|
|
/// picker authors <c>attributeRef = tag.Attr</c>. The transition must resolve to the tag's RawPath (before
|
|
/// the fix it surfaced under the full reference, which matched no condition, so the alarm never went
|
|
/// active), and the ack must dial the provider-qualified reference the gateway accepts.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task Alarm_PickerAuthoredAttributeRef_ResolvesViaSourceObjectReference_AndAcksFullReference()
|
|
{
|
|
const string fullRef = "Galaxy!Area1.Tank1.Level";
|
|
var feed = new FakeAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
using var driver = new GalaxyDriver(
|
|
"g", OptsWithRawTags(), hierarchySource: null, alarmAcknowledger: ack, alarmFeed: feed,
|
|
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
|
await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
var observed = new List<AlarmEventArgs>();
|
|
driver.OnAlarmEvent += (_, args) => observed.Add(args);
|
|
|
|
feed.Emit(NewTransition(fullRef, AttributeRef));
|
|
|
|
observed.ShouldHaveSingleItem();
|
|
observed[0].ConditionId.ShouldBe(RawPath);
|
|
|
|
await driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
|
|
ack.Calls.ShouldHaveSingleItem();
|
|
ack.Calls[0].AlarmRef.ShouldBe(fullRef);
|
|
}
|
|
|
|
/// <summary>lmxopcua#895: with no usable SourceObjectReference the <c>Provider!Area.</c> prefix is stripped
|
|
/// to find the picker-authored tag.</summary>
|
|
[Fact]
|
|
public void ResolveAlarmRawPath_StripsProviderAndArea_WhenSourceReferenceDoesNotMatch()
|
|
{
|
|
using var driver = new GalaxyDriver("g", OptsWithRawTags(), hierarchySource: null);
|
|
|
|
driver.ResolveAlarmRawPath("Galaxy!Area1.Tank1.Level", sourceObjectReference: "").ShouldBe(RawPath);
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe("Galaxy!Area1.Tank1.Level");
|
|
}
|
|
|
|
/// <summary>lmxopcua#895: a tag authored with the full provider-qualified reference still resolves directly,
|
|
/// and an alarm no authored tag matches keeps the identity fallback (nothing learned).</summary>
|
|
[Fact]
|
|
public void ResolveAlarmRawPath_DirectMatchAndUnmatchedIdentity_AreUnchanged()
|
|
{
|
|
var opts = OptsWithRawTags() with
|
|
{
|
|
RawTags = [new RawTagEntry(RawPath, "{\"attributeRef\":\"Galaxy!Area1.Tank1.Level\"}", false)],
|
|
};
|
|
using var driver = new GalaxyDriver("g", opts, hierarchySource: null);
|
|
|
|
driver.ResolveAlarmRawPath("Galaxy!Area1.Tank1.Level", "Tank1.Level").ShouldBe(RawPath);
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe("Galaxy!Area1.Tank1.Level");
|
|
driver.ResolveAlarmRawPath("Galaxy!Area1.Other.Attr", "Other.Attr").ShouldBe("Galaxy!Area1.Other.Attr");
|
|
driver.ToAlarmAckReference("Galaxy!Area1.Other.Attr").ShouldBe("Galaxy!Area1.Other.Attr");
|
|
}
|
|
|
|
// ===== lmxopcua#895 review: area changes, subtag-provider shape, collisions, ack confirmation =====
|
|
|
|
private const string OtherRawPath = "area/line/tank1/level-hand";
|
|
|
|
private static GalaxyDriverOptions Opts(params (string RawPath, string AttributeRef)[] tags) => OptsWithRawTags() with
|
|
{
|
|
RawTags = [.. tags.Select(t => new RawTagEntry(t.RawPath, $"{{\"attributeRef\":\"{t.AttributeRef}\"}}", false))],
|
|
};
|
|
|
|
/// <summary>Galaxy moves a picker-authored tag's object to another area: the transition still resolves (via the
|
|
/// unchanged source reference) and the ack follows the latest area the feed named.</summary>
|
|
[Fact]
|
|
public void PickerForm_AfterReArea_ResolvesAndAckFollowsTheNewArea()
|
|
{
|
|
using var driver = new GalaxyDriver("g", OptsWithRawTags(), hierarchySource: null);
|
|
|
|
driver.ResolveAlarmRawPath("Galaxy!Area1.Tank1.Level", AttributeRef).ShouldBe(RawPath);
|
|
driver.ResolveAlarmRawPath("Galaxy!Area2.Tank1.Level", AttributeRef).ShouldBe(RawPath);
|
|
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe("Galaxy!Area2.Tank1.Level");
|
|
}
|
|
|
|
/// <summary>A tag hand-authored as <c>Galaxy!Area1.tag.Attr</c> keeps resolving after Galaxy re-areas the object
|
|
/// (before the review fix the feed's <c>Galaxy!Area2…</c> matched nothing and every transition was dropped), and
|
|
/// its ack dials the reference the feed now uses.</summary>
|
|
[Fact]
|
|
public void HandAuthoredProviderForm_AfterReArea_ResolvesAndAcksTheNewArea()
|
|
{
|
|
using var driver = new GalaxyDriver("g", Opts((RawPath, "Galaxy!Area1.Tank1.Level")), hierarchySource: null);
|
|
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe("Galaxy!Area1.Tank1.Level");
|
|
driver.ResolveAlarmRawPath("Galaxy!Area2.Tank1.Level", "Tank1.Level").ShouldBe(RawPath);
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe("Galaxy!Area2.Tank1.Level");
|
|
}
|
|
|
|
/// <summary>The gateway's subtag (degraded) provider sends only the object as the source reference. The
|
|
/// area-stripped full reference resolves it, and a reference composed with an empty area
|
|
/// (<c>Galaxy!tag.Attr</c>) resolves through what follows the <c>!</c>.</summary>
|
|
[Theory]
|
|
[InlineData("Galaxy!Area1.Tank1.Level", "Tank1")]
|
|
[InlineData("Galaxy!Tank1.Level", "Tank1")]
|
|
[InlineData("Galaxy!Tank1.Level", "")]
|
|
[InlineData("Galaxy!Area1.Tank1.Level", null)]
|
|
public void SubtagProviderShapes_Resolve(string fullRef, string? source)
|
|
{
|
|
using var driver = new GalaxyDriver("g", OptsWithRawTags(), hierarchySource: null);
|
|
|
|
driver.ResolveAlarmRawPath(fullRef, source).ShouldBe(RawPath);
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe(fullRef);
|
|
}
|
|
|
|
/// <summary>H6-style contained/dotted references: the object's tag_name (not its contained hierarchy) is what
|
|
/// the feed and the picker share, and an alarm attribute nested under another attribute keeps its dots.</summary>
|
|
[Theory]
|
|
[InlineData("TableAlarms_008.RuntimeAlert", "Galaxy!CVDAisle_1.TableAlarms_008.RuntimeAlert", "TableAlarms_008.RuntimeAlert")]
|
|
[InlineData("TableAlarms_008.RuntimeAlert", "Galaxy!CVDAisle_1.TableAlarms_008.RuntimeAlert", "TableAlarms_008")]
|
|
[InlineData("Tank1.Level.HiHi", "Galaxy!Area1.Tank1.Level.HiHi", "Tank1")]
|
|
public void DottedAndContainedReferences_Resolve(string attributeRef, string fullRef, string source)
|
|
{
|
|
using var driver = new GalaxyDriver("g", Opts((RawPath, attributeRef)), hierarchySource: null);
|
|
|
|
driver.ResolveAlarmRawPath(fullRef, source).ShouldBe(RawPath);
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe(fullRef);
|
|
}
|
|
|
|
/// <summary>Feed references that match nothing — or are malformed — keep the identity fallback, never throw, and
|
|
/// teach nothing (no authored RawPath's ack reference changes).</summary>
|
|
[Theory]
|
|
[InlineData("Galaxy!Area1.Other.Attr", "Other.Attr")]
|
|
[InlineData("Galaxy!Area1.Other.Attr", "Other")]
|
|
[InlineData("Galaxy!", "")]
|
|
[InlineData("Galaxy!Area1.", null)]
|
|
[InlineData("NoBang.Tank1", "")]
|
|
[InlineData("", "")]
|
|
public void UnmatchedOrMalformed_KeepsIdentity_AndLearnsNothing(string fullRef, string? source)
|
|
{
|
|
using var driver = new GalaxyDriver("g", OptsWithRawTags(), hierarchySource: null);
|
|
|
|
driver.ResolveAlarmRawPath(fullRef, source).ShouldBe(fullRef);
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe(AttributeRef);
|
|
}
|
|
|
|
/// <summary>The same Galaxy alarm authored twice — picker form and hand-authored provider form. Deterministic: the
|
|
/// exact provider-form match wins while the area matches; any other area surfaces under the picker tag.</summary>
|
|
[Fact]
|
|
public void PickerAndHandAuthoredOfTheSameAlarm_ResolveDeterministically()
|
|
{
|
|
using var driver = new GalaxyDriver(
|
|
"g", Opts((RawPath, AttributeRef), (OtherRawPath, "Galaxy!Area1.Tank1.Level")), hierarchySource: null);
|
|
|
|
driver.ResolveAlarmRawPath("Galaxy!Area1.Tank1.Level", AttributeRef).ShouldBe(OtherRawPath);
|
|
driver.ResolveAlarmRawPath("Galaxy!Area2.Tank1.Level", AttributeRef).ShouldBe(RawPath);
|
|
driver.ToAlarmAckReference(RawPath).ShouldBe("Galaxy!Area2.Tank1.Level");
|
|
driver.ToAlarmAckReference(OtherRawPath).ShouldBe("Galaxy!Area1.Tank1.Level");
|
|
}
|
|
|
|
/// <summary>A transition that arrives while no alarm subscription is registered is not fanned out, but it still
|
|
/// teaches the ack reference (the feed starts before SubscribeAlarmsAsync registers its handle).</summary>
|
|
[Fact]
|
|
public async Task TransitionWithoutSubscription_StillTeachesTheAckReference()
|
|
{
|
|
var feed = new FakeAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
using var driver = new GalaxyDriver(
|
|
"g", OptsWithRawTags(), hierarchySource: null, alarmAcknowledger: ack, alarmFeed: feed,
|
|
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
|
var handle = await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
await driver.UnsubscribeAlarmsAsync(handle, CancellationToken.None);
|
|
var observed = new List<AlarmEventArgs>();
|
|
driver.OnAlarmEvent += (_, args) => observed.Add(args);
|
|
|
|
feed.Emit(NewTransition("Galaxy!Area1.Tank1.Level", AttributeRef));
|
|
await driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
|
|
observed.ShouldBeEmpty();
|
|
ack.Calls.ShouldHaveSingleItem().AlarmRef.ShouldBe("Galaxy!Area1.Tank1.Level");
|
|
}
|
|
|
|
/// <summary>lmxopcua#869 with the picker form: an ack the gateway only SENT is confirmed by Galaxy's acknowledged
|
|
/// transition, which names the provider-qualified reference — the one the ack now dials.</summary>
|
|
[Fact]
|
|
public async Task PickerForm_UnconfirmedAck_IsConfirmedByTheFeedsAcknowledgedTransition()
|
|
{
|
|
const string fullRef = "Galaxy!Area1.Tank1.Level";
|
|
var feed = new FakeAlarmFeed();
|
|
var opts = OptsWithRawTags() with { AlarmAck = new GalaxyAlarmAckOptions { ConfirmTimeoutMs = 120_000 } };
|
|
using var driver = new GalaxyDriver(
|
|
"g", opts, hierarchySource: null, alarmAcknowledger: new UnconfirmedAcknowledger(), alarmFeed: feed,
|
|
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
|
await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
feed.Emit(NewTransition(fullRef, AttributeRef));
|
|
AlarmAcknowledgeRequest[] request = [new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")];
|
|
|
|
await driver.AcknowledgeAsync(request, CancellationToken.None);
|
|
var confirm = driver.ConfirmAcknowledgedAsync(request, CancellationToken.None);
|
|
confirm.IsCompleted.ShouldBeFalse();
|
|
feed.Emit(NewTransition(fullRef, AttributeRef) with { TransitionKind = GalaxyAlarmTransitionKind.Acknowledge });
|
|
|
|
await TestWait.ForAsync(confirm, "the feed's acknowledged transition must confirm the picker-form ack");
|
|
}
|
|
|
|
// ===== lmxopcua#904: a picker-form ack before the feed has named the alarm =====
|
|
|
|
private static GalaxyDriver NewAckDriver(IGalaxyAlarmFeed feed, IGalaxyAlarmAcknowledger ack, GalaxyDriverOptions? opts = null)
|
|
=> new("g", opts ?? OptsWithRawTags(), hierarchySource: null, alarmAcknowledger: ack, alarmFeed: feed,
|
|
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
|
|
|
/// <summary>
|
|
/// lmxopcua#904: after a host restart the condition is restored from LocalDb before the feed's first snapshot
|
|
/// reaches the new driver instance. An ack in that window must wait for the snapshot and dial the
|
|
/// provider-qualified reference it names — in the object's CURRENT area — not the bare <c>tag.Attr</c> the
|
|
/// gateway refuses.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task PickerForm_AckBeforeFeedSnapshot_WaitsForTheSnapshot_AndDialsItsFullReference()
|
|
{
|
|
const string fullRef = "Galaxy!Area2.Tank1.Level";
|
|
var feed = new SnapshotAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
using var driver = NewAckDriver(feed, ack);
|
|
driver.AckSnapshotWait = TimeSpan.FromMinutes(2);
|
|
await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
|
|
var pending = driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
ack.Calls.ShouldBeEmpty(); // nothing dialled while the feed has not named the alarm
|
|
|
|
feed.Emit(NewTransition(fullRef, AttributeRef) with
|
|
{
|
|
TransitionKind = GalaxyAlarmTransitionKind.Retrigger,
|
|
IsRestatement = true,
|
|
});
|
|
feed.CompleteSnapshot();
|
|
await TestWait.ForAsync(pending, "the ack must proceed once the feed snapshot arrives");
|
|
|
|
ack.Calls.ShouldHaveSingleItem().AlarmRef.ShouldBe(fullRef);
|
|
}
|
|
|
|
/// <summary>lmxopcua#904: a snapshot that does not name the alarm (not active in Galaxy) releases the ack at once;
|
|
/// nothing is guessed, the authored reference is dialled as before and the gateway decides.</summary>
|
|
[Fact]
|
|
public async Task PickerForm_SnapshotWithoutTheAlarm_DialsTheAuthoredReference()
|
|
{
|
|
var feed = new SnapshotAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
using var driver = NewAckDriver(feed, ack);
|
|
driver.AckSnapshotWait = TimeSpan.FromMinutes(2);
|
|
await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
|
|
var pending = driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
feed.Emit(NewTransition("Galaxy!Area1.Other.Attr", "Other.Attr"));
|
|
feed.CompleteSnapshot();
|
|
await TestWait.ForAsync(pending, "a completed snapshot must release the ack");
|
|
|
|
ack.Calls.ShouldHaveSingleItem().AlarmRef.ShouldBe(AttributeRef);
|
|
}
|
|
|
|
/// <summary>lmxopcua#904: the wait is bounded — a feed whose snapshot never comes (gateway unreachable) lets the ack
|
|
/// through after <see cref="GalaxyDriver.AckSnapshotWait"/> with the authored reference.</summary>
|
|
[Fact]
|
|
public async Task PickerForm_SnapshotNeverArrives_AckProceedsAfterTheBoundedWait()
|
|
{
|
|
var feed = new SnapshotAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
using var driver = NewAckDriver(feed, ack);
|
|
driver.AckSnapshotWait = TimeSpan.FromMilliseconds(100);
|
|
await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
|
|
await driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
|
|
ack.Calls.ShouldHaveSingleItem().AlarmRef.ShouldBe(AttributeRef);
|
|
}
|
|
|
|
/// <summary>lmxopcua#904: the caller's token cuts the wait, and nothing is dialled.</summary>
|
|
[Fact]
|
|
public async Task PickerForm_AckCancelledWhileWaitingForTheSnapshot_DialsNothing()
|
|
{
|
|
var feed = new SnapshotAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
using var driver = NewAckDriver(feed, ack);
|
|
driver.AckSnapshotWait = TimeSpan.FromMinutes(2);
|
|
await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
|
|
|
await Should.ThrowAsync<OperationCanceledException>(() => driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], cts.Token));
|
|
|
|
ack.Calls.ShouldBeEmpty();
|
|
}
|
|
|
|
/// <summary>lmxopcua#904: no wait where the feed has nothing to add — a provider-form tag already carries the
|
|
/// reference, and a feed that is not running sends no snapshot.</summary>
|
|
[Fact]
|
|
public async Task NoSnapshotWait_ForProviderFormTags_OrWhenTheFeedIsNotRunning()
|
|
{
|
|
var feed = new SnapshotAlarmFeed();
|
|
var ack = new RecordingAcknowledger();
|
|
var providerOpts = OptsWithRawTags() with
|
|
{
|
|
RawTags = [new RawTagEntry(RawPath, "{\"attributeRef\":\"Galaxy!Area1.Tank1.Level\"}", false)],
|
|
};
|
|
using (var driver = NewAckDriver(feed, ack, providerOpts))
|
|
{
|
|
driver.AckSnapshotWait = TimeSpan.FromMinutes(2);
|
|
await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
|
var pending = driver.AcknowledgeAsync(
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
await TestWait.ForAsync(pending, "a provider-form ack must not wait for the snapshot");
|
|
}
|
|
|
|
using (var driver = NewAckDriver(new SnapshotAlarmFeed(), ack))
|
|
{
|
|
driver.AckSnapshotWait = TimeSpan.FromMinutes(2);
|
|
var pending = driver.AcknowledgeAsync( // feed never started: no SubscribeAlarmsAsync
|
|
[new AlarmAcknowledgeRequest("Tank1", RawPath, "ack it")], CancellationToken.None);
|
|
await TestWait.ForAsync(pending, "an ack must not wait on a feed that is not running");
|
|
}
|
|
|
|
ack.Calls.Select(c => c.AlarmRef).ShouldBe(["Galaxy!Area1.Tank1.Level", AttributeRef]);
|
|
}
|
|
|
|
/// <summary>A feed with a snapshot phase the test completes by hand, like <see cref="GatewayGalaxyAlarmFeed"/>.</summary>
|
|
private sealed class SnapshotAlarmFeed : IGalaxyAlarmFeed
|
|
{
|
|
private readonly TaskCompletionSource _snapshot = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
|
public event EventHandler<GalaxyAlarmTransition>? OnAlarmTransition;
|
|
public Task InitialSnapshotCompleted => _snapshot.Task;
|
|
public void Start() { }
|
|
public void Emit(GalaxyAlarmTransition transition) => OnAlarmTransition?.Invoke(this, transition);
|
|
public void CompleteSnapshot() => _snapshot.TrySetResult();
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
|
|
private sealed class UnconfirmedAcknowledger : IGalaxyAlarmAcknowledger
|
|
{
|
|
public Task<GalaxyAckOutcome> AcknowledgeAsync(
|
|
string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken)
|
|
=> Task.FromResult(GalaxyAckOutcome.Unconfirmed("sent; OnWriteComplete not observed"));
|
|
}
|
|
|
|
// ===== helpers / fakes =====
|
|
|
|
private static GalaxyAttribute Attr(string name, int sec)
|
|
=> new() { AttributeName = name, MxDataType = 2 /*Float32*/, SecurityClassification = sec };
|
|
|
|
private static GalaxyObject Obj(string tag, params GalaxyAttribute[] attrs)
|
|
{
|
|
var o = new GalaxyObject { TagName = tag, ContainedName = tag };
|
|
o.Attributes.AddRange(attrs);
|
|
return o;
|
|
}
|
|
|
|
private static GalaxyAlarmTransition NewTransition(string alarmFullReference, string source)
|
|
=> new(
|
|
AlarmFullReference: alarmFullReference,
|
|
SourceObjectReference: source,
|
|
AlarmTypeName: "AnalogLimitAlarm.HiHi",
|
|
TransitionKind: GalaxyAlarmTransitionKind.Raise,
|
|
SeverityBucket: AlarmSeverity.High,
|
|
OpcUaSeverity: 800,
|
|
RawMxAccessSeverity: 750,
|
|
OriginalRaiseTimestampUtc: null,
|
|
TransitionTimestampUtc: DateTime.UtcNow,
|
|
OperatorUser: string.Empty,
|
|
OperatorComment: string.Empty,
|
|
Category: "Process",
|
|
Description: "high level");
|
|
|
|
private sealed class FakeHierarchySource(IReadOnlyList<GalaxyObject> objects) : IGalaxyHierarchySource
|
|
{
|
|
public Task<IReadOnlyList<GalaxyObject>> GetHierarchyAsync(CancellationToken cancellationToken)
|
|
=> Task.FromResult(objects);
|
|
}
|
|
|
|
/// <summary>Minimal builder — discovery only needs the SecurityCapturingBuilder wrapper to run.</summary>
|
|
private sealed class CapturingBuilder : IAddressSpaceBuilder
|
|
{
|
|
public IAddressSpaceBuilder Folder(string browseName, string displayName) => this;
|
|
public IVariableHandle Variable(string browseName, string displayName, DriverAttributeInfo attributeInfo)
|
|
=> new Handle(attributeInfo.FullName);
|
|
public void AddProperty(string browseName, DriverDataType dataType, object? value) { }
|
|
|
|
private sealed class Handle(string fullRef) : IVariableHandle
|
|
{
|
|
public string FullReference { get; } = fullRef;
|
|
public IAlarmConditionSink MarkAsAlarmCondition(AlarmConditionInfo info) => new Sink();
|
|
private sealed class Sink : IAlarmConditionSink { public void OnTransition(AlarmEventArgs args) { } }
|
|
}
|
|
}
|
|
|
|
private sealed class RecordingReader : IGalaxyDataReader
|
|
{
|
|
public IReadOnlyList<string>? LastRequest { get; private set; }
|
|
|
|
public Task<IReadOnlyList<DataValueSnapshot>> ReadAsync(
|
|
IReadOnlyList<string> fullReferences, CancellationToken cancellationToken)
|
|
{
|
|
LastRequest = fullReferences;
|
|
return Task.FromResult<IReadOnlyList<DataValueSnapshot>>(
|
|
fullReferences.Select(_ => new DataValueSnapshot(0.0, StatusCodeMap.Good, null, DateTime.UtcNow)).ToArray());
|
|
}
|
|
}
|
|
|
|
private sealed class RecordingWriter : IGalaxyDataWriter
|
|
{
|
|
public List<(string FullRef, object? Value, SecurityClassification Resolved)> Calls { get; } = [];
|
|
|
|
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
|
IReadOnlyList<WriteRequest> writes,
|
|
Func<string, SecurityClassification> securityResolver,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var results = new WriteResult[writes.Count];
|
|
for (var i = 0; i < writes.Count; i++)
|
|
{
|
|
Calls.Add((writes[i].FullReference, writes[i].Value, securityResolver(writes[i].FullReference)));
|
|
results[i] = new WriteResult(StatusCodeMap.Good);
|
|
}
|
|
return Task.FromResult<IReadOnlyList<WriteResult>>(results);
|
|
}
|
|
|
|
public void InvalidateHandleCaches() { }
|
|
}
|
|
|
|
private sealed class FakeAlarmFeed : IGalaxyAlarmFeed
|
|
{
|
|
public event EventHandler<GalaxyAlarmTransition>? OnAlarmTransition;
|
|
public void Start() { }
|
|
public void Emit(GalaxyAlarmTransition transition) => OnAlarmTransition?.Invoke(this, transition);
|
|
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
|
}
|
|
|
|
private sealed class RecordingAcknowledger : IGalaxyAlarmAcknowledger
|
|
{
|
|
public List<(string AlarmRef, string Comment, string Operator)> Calls { get; } = [];
|
|
|
|
public Task<GalaxyAckOutcome> AcknowledgeAsync(string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken)
|
|
{
|
|
Calls.Add((alarmFullReference, comment, credential.User));
|
|
return Task.FromResult(GalaxyAckOutcome.Applied);
|
|
}
|
|
}
|
|
|
|
/// <summary>Two RawPaths sharing one attributeRef: first wins the reverse map, the loser is recorded in the skipped ledger (06/S-13).</summary>
|
|
[Fact]
|
|
public void DuplicateAttributeRef_RecordsLosingRawPath_InSkippedLedger()
|
|
{
|
|
var opts = OptsWithRawTags() with
|
|
{
|
|
RawTags =
|
|
[
|
|
new RawTagEntry(RawPath, $"{{\"attributeRef\":\"{AttributeRef}\"}}", false),
|
|
new RawTagEntry("area/line/tank1/level-copy", $"{{\"attributeRef\":\"{AttributeRef}\"}}", false),
|
|
],
|
|
};
|
|
using var driver = new GalaxyDriver("g", opts, hierarchySource: null);
|
|
|
|
var report = driver.GetSkippedTags();
|
|
report.ShouldNotBeNull();
|
|
report.AuthoredCount.ShouldBe(2);
|
|
report.SkippedCount.ShouldBe(1);
|
|
report.Sample[0].RawPath.ShouldBe("area/line/tank1/level-copy");
|
|
report.Sample[0].Reason.ShouldContain(RawPath);
|
|
}
|
|
}
|