fix(history): a folder's event history reads the Galaxy objects behind its native conditions (#886)
v2-ci / unit-tests (push) Has been cancelled
v2-ci / unit-tests (push) Has been cancelled
A notifier folder read one event source, its NodeId identifier (a RawPath or an EquipmentId). AVEVA stores a Galaxy object's A&E history under the object's tag_name (Source_Object), so AVEVA's own alarm and event history reached no production folder. Its lower-case property keys were also missed, so every row read Severity 1 with no ConditionName. Sources. A folder's event history now reads its own source plus the Galaxy object of every native condition that fires on it live: those parented under it and those WireAlarmNotifiers wired to it. Live and history use the same membership. The object comes from the condition's Galaxy alarm reference, its raw tag's attributeRef, up to the first '.': - The composer reads it with the driver's own parser (GalaxyAttributeRef, shared with GalaxyDriver), only for a GalaxyMxGateway tag with an alarm (RawTagPlan.NativeAlarmReference, part of plan equality). - The applier binds it after materialising the condition (IOpcUaAddressSpaceSink.BindNativeAlarmHistory, forwarded by the deferred sink). A rebuild or the condition's removal forgets it. Each object is read with the #882 rule: its own events and <Object>.<Attribute> rows, never a prefix sibling. Fan-out. historiangw's ReadEvents filter is a single predicate, so there is one request per source; the wire contract is unchanged. EventSourceFanOut merges the reads as one source: - order is (time, source position, arrival), reversed for a reverse read; ties are never re-sorted by EventId, so the boundary skip stays stable; - duplicates by EventId are dropped and the merge is cut to the cap; - a truncated source bounds the page at the time it stopped. Paging, continuation points (bound to the whole source set), the walked-back reverse read and the tie-cluster over-fetch are unchanged. A folder with one source is read exactly as before. ACL. Every source is read inside the folder's own HistoryRead, after AuthorizeHistoryRead (#826). A denied folder reads nothing and fails closed. Mapping (EventMapper, property names now case-insensitive): - Severity: an AVEVA row's priority goes through GalaxyAlarmPriority, the table live Galaxy alarms use (MxAccessSeverityMapper now delegates to it), so history matches live. Otherwise severity (OtOpcUa's own rows, which AVEVA stores lower-cased), clamped. AVEVA's own 1-4 severity is ignored. The table ranks a higher priority as more severe, which inverts AVEVA's convention: filed as #887. - An AVEVA row whose source_conditionvariable names a native condition that fires on the folder takes that condition's SourceNode and live ConditionName. Otherwise ConditionName is alarmname or the condition variable's attribute. - alarm_id/alarmid map to AlarmId. Tests: - GalaxyEquipmentEventHistoryWireTests (4, real SDK session, production Gateway backend, AVEVA-shaped fake gateway): equipment EqA backed by objects Oven_007 + OvenDoor_07. Covers object and attribute events from both objects, the prefix sibling excluded, cross-object and in-object ties, forward paging at 1-4 a page, reverse whole and paged, SourceNode/ConditionName/Severity, the raw device folder, ACL deny with no backend call plus a granted positive control, and a rebuild forgetting the bindings. - EventSourceFanOutTests (8), EventMapper AVEVA cases (11), GalaxyAttributeRefTests (16), a composer test and an applier ordering test. - Mutation-checked, 17 mutants, all killed. Covered: parent-only membership, no scope, a case-sensitive condition match, no condition rewrite, no truncation bound, EventId tie order, no sort, no cap, no stop at the bound, unreversed source order, no dedupe, no '.' boundary, priority ignored, case-sensitive keys, no applier bind, no deferred forward, and a composer that ignores the driver type. The forget-on-rematerialise guard survives as belt-and-braces: the rebuild clear covers it. - Live, read-only, no WinRM, vd03 HistorianGateway ea9f21c: equipment folder EQ-886-ZipsenLeft (objects DevWinPlatform + Left_001). It read 0 events before and 92 now, equal to the unfiltered read's rows for both objects. 1/7-event pages and reverse whole/5-event pages agree, and 73 rows resolve to their live condition. diff_runs vs the #882 run: 221/226 identical. The 5 that differ are expected: DevWinPlatform Severity 1 -> 750/1000, and #881 capabilities. Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
+147
-1
@@ -33,7 +33,9 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
|
||||
/// <c>OTOPCUA_AVEVA_GATE_OUT</c> (output directory for <c>aveva-gate-*.json</c>), <c>OTOPCUA_AVEVA_GATE_LABEL</c>
|
||||
/// (a run label recorded in the output, e.g. the SDK version), <c>OTOPCUA_AVEVA_GATE_TAGS</c> (comma list of
|
||||
/// historized analog tags), <c>OTOPCUA_AVEVA_GATE_WINDOWS</c> (<c>start/end;start/end</c>, ISO-8601 UTC),
|
||||
/// <c>OTOPCUA_AVEVA_GATE_EVENT_SOURCES</c> (comma list) and <c>OTOPCUA_AVEVA_GATE_EVENT_WINDOW</c>. The defaults are the DEV
|
||||
/// <c>OTOPCUA_AVEVA_GATE_EVENT_SOURCES</c> (comma list), <c>OTOPCUA_AVEVA_GATE_EVENT_WINDOW</c> and
|
||||
/// <c>OTOPCUA_AVEVA_GATE_GALAXY_REFS</c> (#886: comma list of Galaxy alarm references whose native conditions are wired to
|
||||
/// one equipment folder that is not named after any of their objects). The defaults are the DEV
|
||||
/// (wonder-app-vd03 / wonder-sql-vd03) tags and fixed past windows used for the 2026-11-12 run.</para>
|
||||
/// <para>The local deterministic fixtures are NOT this test; only a real gateway in front of a real AVEVA
|
||||
/// Historian makes its output AVEVA evidence.</para>
|
||||
@@ -53,6 +55,12 @@ public sealed class AvevaGatewayHistoryLiveGateTests
|
||||
// it stays GoodNoData. Recorded (wire must equal the backend), not required to be non-empty.
|
||||
private const string DefaultEventSources = "DevWinPlatform,DevWinPlatform.CPULoadAvg";
|
||||
private const string DefaultEventWindow = "2026-11-05T15:00:00Z/2026-11-12T00:00:00Z";
|
||||
|
||||
// #886: a REAL equipment folder — its id is not a Galaxy object name — whose native conditions dial these Galaxy alarm
|
||||
// references (attributeRef). Two objects with A&E history on DEV in the event window: the platform's CPU-load alarm
|
||||
// and a ZIPSEN Left_001 machine alarm. The folder must serve both objects' events and attribute alarms.
|
||||
private const string DefaultGalaxyAlarmRefs = "DevWinPlatform.CPULoadHiAlarm,Left_001.FRR_Warning";
|
||||
private const string GalaxyEquipment = "EQ-886-ZipsenLeft";
|
||||
private const string MissingTag = "OtOpcUa.Gate801.DoesNotExist";
|
||||
private const double IntervalMs = 60_000;
|
||||
|
||||
@@ -99,6 +107,8 @@ public sealed class AvevaGatewayHistoryLiveGateTests
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
var eventWindow = ParseWindows(Env("OTOPCUA_AVEVA_GATE_EVENT_WINDOW") ?? DefaultEventWindow)[0];
|
||||
var sandboxTag = Env("HISTGW_WRITE_SANDBOX_TAG");
|
||||
var galaxyRefs = (Env("OTOPCUA_AVEVA_GATE_GALAXY_REFS") ?? DefaultGalaxyAlarmRefs)
|
||||
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
// The production backend path: the same registry + provider + factory the Host uses for Backend=Gateway.
|
||||
var options = new ServerHistorianOptions
|
||||
@@ -142,6 +152,23 @@ public sealed class AvevaGatewayHistoryLiveGateTests
|
||||
AddressSpaceRealm.Raw, isNative: true);
|
||||
}
|
||||
|
||||
// #886: the applier's shape for a Galaxy deployment — each native condition under its raw device folder, bound to
|
||||
// its Galaxy alarm reference and wired to the one equipment folder that references both.
|
||||
rig.Sink.EnsureFolder(GalaxyEquipment, parentNodeId: null, displayName: "ZIPSEN Left line", realm: AddressSpaceRealm.Uns);
|
||||
var galaxyConditions = new Dictionary<string, (string RawPath, string Name)>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var reference in galaxyRefs)
|
||||
{
|
||||
var objectName = GalaxyAttributeRef.ObjectNameOf(reference)!;
|
||||
var name = reference[(reference.IndexOf('.') + 1)..].Replace(".", "_", StringComparison.Ordinal);
|
||||
var deviceFolder = $"Plant/Galaxy/{objectName}";
|
||||
var rawPath = $"{deviceFolder}/{name}";
|
||||
rig.Sink.EnsureFolder(deviceFolder, parentNodeId: null, displayName: objectName, realm: AddressSpaceRealm.Raw);
|
||||
rig.Sink.MaterialiseAlarmCondition(rawPath, deviceFolder, name, "OffNormalAlarm", 500, AddressSpaceRealm.Raw, isNative: true);
|
||||
rig.Sink.BindNativeAlarmHistory(rawPath, AddressSpaceRealm.Raw, reference);
|
||||
rig.Sink.WireAlarmNotifiers(rawPath, AddressSpaceRealm.Raw, [GalaxyEquipment], AddressSpaceRealm.Uns);
|
||||
galaxyConditions[reference] = (rawPath, name);
|
||||
}
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: true, ct);
|
||||
var ns = (ushort)session.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri);
|
||||
NodeId Node(string id) => new(id, ns);
|
||||
@@ -299,6 +326,78 @@ public sealed class AvevaGatewayHistoryLiveGateTests
|
||||
}
|
||||
}
|
||||
|
||||
// ---- #886: a real equipment folder serves the AVEVA history of every Galaxy object behind its native conditions.
|
||||
{
|
||||
var (start, end) = eventWindow;
|
||||
var w = $"{start:o}/{end:o}";
|
||||
var objects = galaxyRefs.Select(r => GalaxyAttributeRef.ObjectNameOf(r)!).Distinct(StringComparer.Ordinal).ToList();
|
||||
var discovered = await source.ReadEventsAsync(null, start, end, 0, ct);
|
||||
bool OfAnObject(string? s) => s is not null && objects.Any(o => s == o || s.StartsWith(o + ".", StringComparison.Ordinal));
|
||||
var expected = discovered.Events.Where(e => OfAnObject(e.SourceName)).ToList();
|
||||
// The backend's own mapping of each event (per object, as the folder reads them): severity and AVEVA's condition.
|
||||
var direct = new Dictionary<string, HistoricalEvent>(StringComparer.Ordinal);
|
||||
foreach (var o in objects)
|
||||
foreach (var e in (await source.ReadEventsAsync(o, start, end, 0, ct)).Events) direct.TryAdd(e.EventId, e);
|
||||
var folderOwn = await source.ReadEventsAsync(GalaxyEquipment, start, end, 0, ct);
|
||||
|
||||
var uns = new NodeId(GalaxyEquipment, (ushort)session.NamespaceUris.GetIndex(V3NodeIds.UnsNamespaceUri));
|
||||
var all = await ReadGalaxyEventsAsync(session, uns, start, end, 0, ct);
|
||||
var paged1 = await ReadGalaxyEventsAsync(session, uns, start, end, 1, ct);
|
||||
var paged7 = await ReadGalaxyEventsAsync(session, uns, start, end, 7, ct);
|
||||
var reverse = await ReadGalaxyEventsAsync(session, uns, end, start, 0, ct);
|
||||
var reverse5 = await ReadGalaxyEventsAsync(session, uns, end, start, 5, ct);
|
||||
|
||||
var bySource = string.Join(",", all.Rows.GroupBy(r => r.Event.Source ?? "<null>").OrderBy(g => g.Key, StringComparer.Ordinal)
|
||||
.Select(g => $"{g.Key}={g.Count()}"));
|
||||
var resolved = all.Rows.Count(r => r.SourceNode is not null);
|
||||
report.Add(new Case("events886.folderOwnSourceOnly", GalaxyEquipment, w, "direct", "Good",
|
||||
$"events={folderOwn.Events.Count} (what the folder read before #886)", null));
|
||||
report.Add(new Case("events886.all", GalaxyEquipment, w, "wire", all.Status,
|
||||
$"pages={all.Pages} objects={string.Join('+', objects)} bySource={bySource} sourceNodeResolved={resolved}", null, null,
|
||||
all.Rows.Select(r => r.Event).ToList()));
|
||||
report.Add(new Case("events886.paged1", GalaxyEquipment, w, "wire", paged1.Status, $"pages={paged1.Pages}", null, null,
|
||||
paged1.Rows.Select(r => r.Event).ToList()));
|
||||
report.Add(new Case("events886.paged7", GalaxyEquipment, w, "wire", paged7.Status, $"pages={paged7.Pages}", null, null,
|
||||
paged7.Rows.Select(r => r.Event).ToList()));
|
||||
report.Add(new Case("events886.reverse", GalaxyEquipment, w, "wire", reverse.Status, $"pages={reverse.Pages}", null, null,
|
||||
reverse.Rows.Select(r => r.Event).ToList()));
|
||||
report.Add(new Case("events886.reverse5", GalaxyEquipment, w, "wire", reverse5.Status, $"pages={reverse5.Pages}", null, null,
|
||||
reverse5.Rows.Select(r => r.Event).ToList()));
|
||||
report.Add(new Case("events886.conditions", GalaxyEquipment, w, "wire", all.Status,
|
||||
string.Join(";", all.Rows.Where(r => r.SourceNode is not null).GroupBy(r => (r.SourceNode, r.ConditionName))
|
||||
.Select(g => $"{g.Key.SourceNode}|{g.Key.ConditionName}={g.Count()}")), null));
|
||||
|
||||
foreach (var o in objects)
|
||||
Check(failures, expected.Any(e => e.SourceName == o || e.SourceName!.StartsWith(o + ".", StringComparison.Ordinal)),
|
||||
$"events886 {o} {w}: expected stored events for every object behind the folder");
|
||||
Check(failures, folderOwn.Events.Count == 0, $"events886: the folder id {GalaxyEquipment} must name no AVEVA source");
|
||||
var expectedIds = expected.Select(e => e.EventId).OrderBy(id => id, StringComparer.Ordinal).ToList();
|
||||
Check(failures, all.Rows.Select(r => r.Event.Id).OrderBy(id => id, StringComparer.Ordinal).SequenceEqual(expectedIds),
|
||||
$"events886 {w}: wire {all.Rows.Count} events vs {expectedIds.Count} of {string.Join('/', objects)} or their attributes");
|
||||
Check(failures, all.Rows.Zip(all.Rows.Skip(1)).All(p => p.First.Event.Time <= p.Second.Event.Time),
|
||||
"events886: a forward read is in time order across objects");
|
||||
var forwardIds = all.Rows.Select(r => r.Event.Id).ToList();
|
||||
Check(failures, paged1.Rows.Select(r => r.Event.Id).SequenceEqual(forwardIds), "events886: 1-event pages equal the whole read");
|
||||
Check(failures, paged7.Rows.Select(r => r.Event.Id).SequenceEqual(forwardIds), "events886: 7-event pages equal the whole read");
|
||||
var reverseIds = expected.OrderByDescending(e => e.EventTimeUtc).ThenByDescending(e => e.EventId, StringComparer.Ordinal)
|
||||
.Select(e => e.EventId).ToList();
|
||||
Check(failures, reverse.Rows.Select(r => r.Event.Id).SequenceEqual(reverseIds),
|
||||
"events886: a reverse read is newest first (ties by EventId, descending)");
|
||||
Check(failures, reverse5.Rows.Select(r => r.Event.Id).SequenceEqual(reverseIds), "events886: 5-event reverse pages equal the reverse read");
|
||||
foreach (var r in all.Rows)
|
||||
{
|
||||
if (!direct.TryGetValue(r.Event.Id!, out var d)) { failures.Add($"events886: {r.Event.Id} not in the per-object read"); continue; }
|
||||
Check(failures, r.Event.Severity == d.Severity, $"events886: {r.Event.Id} severity {r.Event.Severity} vs backend {d.Severity}");
|
||||
var live = d.ConditionReference is { } cr && galaxyConditions.TryGetValue(cr, out var c) ? c : ((string RawPath, string Name)?)null;
|
||||
Check(failures, r.SourceNode == live?.RawPath,
|
||||
$"events886: {r.Event.Id} ({d.ConditionReference}) SourceNode {r.SourceNode ?? "null"} vs {live?.RawPath ?? "null"}");
|
||||
if (live is { } lc)
|
||||
Check(failures, r.ConditionName == lc.Name, $"events886: {r.Event.Id} ConditionName {r.ConditionName} vs {lc.Name}");
|
||||
}
|
||||
|
||||
Check(failures, resolved > 0, "events886: at least one row resolves to its live condition");
|
||||
}
|
||||
|
||||
// ---- HistoryUpdate: refused by the server (no updater, no HistoryWrite bit). Sandbox-bound node only.
|
||||
if (sandboxNode is null)
|
||||
{
|
||||
@@ -463,6 +562,49 @@ public sealed class AvevaGatewayHistoryLiveGateTests
|
||||
return new EventRead(status, rows, pages);
|
||||
}
|
||||
|
||||
/// <summary>#886: an events read that also returns the SourceNode and ConditionName (paged by continuation points).</summary>
|
||||
private static async Task<GalaxyEventRead> ReadGalaxyEventsAsync(ISession session, NodeId node, DateTime start, DateTime end, uint page,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var filter = new EventFilter();
|
||||
foreach (var field in new[] { "EventId", "Time", "ReceiveTime", "SourceName", "Message", "Severity", "SourceNode", "ConditionName" })
|
||||
{
|
||||
var type = field == "ConditionName" ? ObjectTypeIds.ConditionType : ObjectTypeIds.BaseEventType;
|
||||
filter.SelectClauses += new SimpleAttributeOperand(type, new QualifiedName(field)) { AttributeId = Attributes.Value };
|
||||
}
|
||||
|
||||
var details = new ReadEventDetails { StartTime = start, EndTime = end, NumValuesPerNode = page, Filter = filter };
|
||||
var rows = new List<GalaxyEventRow>();
|
||||
var pages = 0;
|
||||
ByteString cp = default;
|
||||
string status;
|
||||
do
|
||||
{
|
||||
var response = await session.HistoryReadAsync(null, new ExtensionObject(details), TimestampsToReturn.Both, false,
|
||||
new HistoryReadValueId[] { new() { NodeId = node, ContinuationPoint = cp } }, ct);
|
||||
var result = response.Results.ToList().ShouldHaveSingleItem();
|
||||
status = Name(result.StatusCode);
|
||||
cp = result.ContinuationPoint;
|
||||
pages++;
|
||||
if (!result.HistoryData.IsNull && ExtensionObject.ToEncodeable(result.HistoryData) is HistoryEvent he)
|
||||
foreach (var e in he.Events.ToList())
|
||||
{
|
||||
var f = e.EventFields.ToList();
|
||||
rows.Add(new GalaxyEventRow(
|
||||
new EventRow(
|
||||
f[0].ClrValue() is byte[] id ? System.Text.Encoding.UTF8.GetString(id) : Fmt(f[0].ClrValue()),
|
||||
f[1].ClrValue() as DateTime? ?? default, f[2].ClrValue() as DateTime? ?? default,
|
||||
f[3].ClrValue() as string, f[4].ClrValue() is LocalizedText lt ? lt.Text : Fmt(f[4].ClrValue()),
|
||||
Convert.ToUInt16(f[5].ClrValue() ?? 0, CultureInfo.InvariantCulture)),
|
||||
f[6].ClrValue() is NodeId sn && !sn.IsNull ? sn.IdentifierAsString : null,
|
||||
f[7].ClrValue() as string));
|
||||
}
|
||||
if (status.StartsWith("Bad", StringComparison.Ordinal)) break;
|
||||
}
|
||||
while (!cp.IsEmpty && pages < 10_000);
|
||||
return new GalaxyEventRead(status, rows, pages);
|
||||
}
|
||||
|
||||
private static async Task<Dictionary<string, string?>> ReadAttributesAsync(ISession session, NodeId node, CancellationToken ct)
|
||||
{
|
||||
var ids = new (string Name, uint Id)[]
|
||||
@@ -586,6 +728,10 @@ public sealed class AvevaGatewayHistoryLiveGateTests
|
||||
|
||||
private sealed record EventRead(string Status, List<EventRow> Rows, int Pages);
|
||||
|
||||
private sealed record GalaxyEventRow(EventRow Event, string? SourceNode, string? ConditionName);
|
||||
|
||||
private sealed record GalaxyEventRead(string Status, List<GalaxyEventRow> Rows, int Pages);
|
||||
|
||||
private sealed record Case(
|
||||
string Name, string? Tag, string? Window, string Path, string Status, string? Note,
|
||||
Dictionary<string, string?>? Attributes, List<Row>? Rows = null, List<EventRow>? Events = null);
|
||||
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.HistorianGateway.Contracts.Grpc;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway;
|
||||
using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #886 over a real SDK session, with the production Gateway backend on a deterministic AVEVA-shaped gateway: a
|
||||
/// REAL equipment folder — whose id (<c>EqA</c>) is not a Galaxy object name — serves the AVEVA history of the Galaxy
|
||||
/// objects behind its native conditions, here two (<c>Oven_007</c> and <c>OvenDoor_07</c>): each object's own events
|
||||
/// and its attribute alarms, never a prefix sibling (<c>Oven_0070</c>), merged in time order across paging and reverse
|
||||
/// reads, with the live condition's SourceNode / ConditionName and the live Galaxy severity, and only behind the
|
||||
/// folder's own HistoryRead verdict.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Topology, as the applier builds it from a Galaxy deployment: raw folder <c>Plant/Galaxy/Oven7</c> holds two native
|
||||
/// conditions, <c>TempHi</c> (attributeRef <c>Oven_007.TempHiAlarm</c>) and <c>DoorOpen</c>
|
||||
/// (<c>OvenDoor_07.DoorAlarm</c>), both wired to equipment <c>EqA</c>; raw folder <c>Plant/Galaxy/Line3</c> holds
|
||||
/// <c>Jam</c> (<c>Line3_Conveyor.JamAlarm</c>), wired to <c>EqB</c>. The fake gateway filters a per-source read more
|
||||
/// loosely than the real one (<c>Source_Object</c> begins with the source), so the sibling's rows reach OtOpcUa and
|
||||
/// their absence is OtOpcUa's filter at work.
|
||||
/// </remarks>
|
||||
public sealed class GalaxyEquipmentEventHistoryWireTests
|
||||
{
|
||||
private const string OvenFolder = "Plant/Galaxy/Oven7";
|
||||
private const string LineFolder = "Plant/Galaxy/Line3";
|
||||
private const string TempHi = OvenFolder + "/TempHi";
|
||||
private const string DoorOpen = OvenFolder + "/DoorOpen";
|
||||
private const string Jam = LineFolder + "/Jam";
|
||||
|
||||
private static readonly DateTime Epoch = new(2026, 11, 10, 11, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
/// <summary>The stored AVEVA rows. A null condition variable is an object-level system event.</summary>
|
||||
private static readonly AvevaRow[] Stored =
|
||||
[
|
||||
new("o-stop", "Oven_007", "Oven_007", "System.Stop", 0, 999, null),
|
||||
new("l-set", "Line3_Conveyor.Belt", "Line3_Conveyor", "Alarm.Set", 1, 300, "Line3_Conveyor.JamAlarm"),
|
||||
new("o-temp-set", "Oven_007.Temp", "Oven_007", "Alarm.Set", 2, 500, "Oven_007.TempHiAlarm"),
|
||||
new("d-set", "OvenDoor_07.Door", "OvenDoor_07", "Alarm.Set", 2, 700, "OvenDoor_07.DoorAlarm"), // a tie across objects
|
||||
new("a-oven-tie", "Oven_007.Temp", "Oven_007", "Alarm.Ack", 2, 500, "Oven_007.TempHiAlarm"), // and within one, stored later
|
||||
new("o-press-set", "Oven_007.Pressure", "Oven_007", "Alarm.Set", 3, 100, "Oven_007.PressureHiAlarm"), // no live condition here
|
||||
new("s-set", "Oven_0070.Temp", "Oven_0070", "Alarm.Set", 4, 500, "Oven_0070.TempHiAlarm"), // prefix sibling
|
||||
new("d-clear", "OvenDoor_07.Door", "OvenDoor_07", "Alarm.Clear", 5, 700, "OvenDoor_07.DoorAlarm"),
|
||||
new("o-temp-clear", "Oven_007.Temp", "Oven_007", "Alarm.Clear", 6, 500, "oven_007.temphialarm"), // Galaxy names: any case
|
||||
new("l-clear", "Line3_Conveyor.Belt", "Line3_Conveyor", "Alarm.Clear", 7, 300, "Line3_Conveyor.JamAlarm"),
|
||||
new("o-start", "Oven_007", "Oven_007", "System.Start", 8, 999, null),
|
||||
];
|
||||
|
||||
/// <summary>EqA's events forward: by time, then source (the folder's ordinal-sorted list: <c>OvenDoor_07</c> before
|
||||
/// <c>Oven_007</c>), then the order the gateway returned them in — so <c>a-oven-tie</c> follows <c>o-temp-set</c>.</summary>
|
||||
private static readonly string[] EqAEvents =
|
||||
["o-stop", "d-set", "o-temp-set", "a-oven-tie", "o-press-set", "d-clear", "o-temp-clear", "o-start"];
|
||||
|
||||
/// <summary>EqA's events reverse: newest first; the Gateway's walked-back reverse read orders ties by EventId,
|
||||
/// descending, as it did before #886.</summary>
|
||||
private static readonly string[] EqAEventsReverse =
|
||||
["o-start", "o-temp-clear", "d-clear", "o-press-set", "o-temp-set", "d-set", "a-oven-tie", "o-stop"];
|
||||
|
||||
[Fact]
|
||||
public async Task An_equipment_folder_serves_the_aveva_history_of_every_galaxy_object_behind_it()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await StartAsync("GalaxyEqHistory", encrypted: false, ct);
|
||||
var gateway = new AvevaShapedGateway();
|
||||
rig.Nm.HistorianDataSource = new GatewayHistorianDataSource(gateway, NullLogger<GatewayHistorianDataSource>.Instance);
|
||||
Materialise(rig);
|
||||
rig.Enforce(false, [Key()]);
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: true, ct);
|
||||
var all = await ReadAsync(session, Uns(session, EqA), forward: true, page: 0, ct);
|
||||
|
||||
all.Status.ShouldBe(StatusCodes.Good);
|
||||
all.Rows.Select(r => r.Id).ShouldBe(EqAEvents);
|
||||
gateway.Requested.ShouldBe(new[] { EqA, "OvenDoor_07", "Oven_007" },
|
||||
"the folder's own source and one request per Galaxy object behind it (no multi-source request exists)");
|
||||
gateway.Yielded.ShouldContain("s-set", "the sibling's rows reached OtOpcUa, so their absence is its filter's doing");
|
||||
|
||||
var byId = all.Rows.ToDictionary(r => r.Id);
|
||||
// Each event keeps the source the historian reported.
|
||||
byId["o-temp-set"].Source.ShouldBe("Oven_007.Temp");
|
||||
byId["o-stop"].Source.ShouldBe("Oven_007");
|
||||
// A row naming a condition that fires on this folder carries that live condition (any-case reference).
|
||||
byId["o-temp-set"].SourceNode.ShouldBe(TempHi);
|
||||
byId["o-temp-clear"].SourceNode.ShouldBe(TempHi);
|
||||
byId["o-temp-set"].ConditionName.ShouldBe("TempHi");
|
||||
byId["d-set"].SourceNode.ShouldBe(DoorOpen);
|
||||
byId["d-set"].ConditionName.ShouldBe("DoorOpen");
|
||||
// An alarm of the object with no condition wired here: served (object rule), but names no node.
|
||||
byId["o-press-set"].SourceNode.ShouldBeNull();
|
||||
byId["o-press-set"].ConditionName.ShouldBe("PressureHiAlarm");
|
||||
// A system event has no condition at all.
|
||||
byId["o-stop"].SourceNode.ShouldBeNull();
|
||||
byId["o-stop"].ConditionName.ShouldBeNull();
|
||||
// Severity follows the live Galaxy table (priority 500 → 750, 700 → 750, 100 → 250, 999 → 1000), not Severity 1.
|
||||
byId["o-temp-set"].Severity.ShouldBe((ushort)750);
|
||||
byId["d-set"].Severity.ShouldBe((ushort)750);
|
||||
byId["o-press-set"].Severity.ShouldBe((ushort)250);
|
||||
byId["o-stop"].Severity.ShouldBe((ushort)1000);
|
||||
|
||||
// The raw device folder the conditions hang under reads the same objects (live: a condition fires on its parent).
|
||||
var raw = await ReadAsync(session, Raw(session, OvenFolder), forward: true, page: 0, ct);
|
||||
raw.Rows.Select(r => r.Id).ShouldBe(EqAEvents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Paging_and_reverse_reads_walk_the_merged_sources_exactly_once()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await StartAsync("GalaxyEqHistoryPaging", encrypted: false, ct);
|
||||
var gateway = new AvevaShapedGateway();
|
||||
rig.Nm.HistorianDataSource = new GatewayHistorianDataSource(gateway, NullLogger<GatewayHistorianDataSource>.Instance);
|
||||
Materialise(rig);
|
||||
rig.Enforce(false, [Key()]);
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: true, ct);
|
||||
var node = Uns(session, EqA);
|
||||
foreach (var page in new uint[] { 1, 2, 3, 4 })
|
||||
{
|
||||
var paged = await ReadAsync(session, node, forward: true, page, ct);
|
||||
paged.Rows.Select(r => r.Id).ShouldBe(EqAEvents, $"forward, {page} a page");
|
||||
paged.Pages.ShouldBeGreaterThan(1);
|
||||
|
||||
var reverse = await ReadAsync(session, node, forward: false, page, ct);
|
||||
reverse.Rows.Select(r => r.Id).ShouldBe(EqAEventsReverse, $"reverse, {page} a page (newest first, ties descending)");
|
||||
}
|
||||
|
||||
var reverseWhole = await ReadAsync(session, node, forward: false, page: 0, ct);
|
||||
reverseWhole.Rows.Select(r => r.Id).ShouldBe(EqAEventsReverse);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task With_the_acl_on_a_denied_folder_reads_none_of_its_galaxy_objects()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await StartAsync("GalaxyEqHistoryAcl", encrypted: false, ct);
|
||||
var gateway = new AvevaShapedGateway();
|
||||
rig.Nm.HistorianDataSource = new GatewayHistorianDataSource(gateway, NullLogger<GatewayHistorianDataSource>.Instance);
|
||||
Materialise(rig);
|
||||
// Anonymous is granted EqB only: EqA, behind which sit Oven_007 and OvenDoor_07, is denied.
|
||||
rig.Enforce(true, [Key()], EquipmentGrant(EqB, NodePermissions.ReadOnly));
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: true, ct);
|
||||
var denied = await ReadAsync(session, Uns(session, EqA), forward: true, page: 0, ct);
|
||||
|
||||
denied.Status.ShouldBe(StatusCodes.BadUserAccessDenied);
|
||||
denied.HistoryDataIsNull.ShouldBeTrue("a denied folder discloses none of its events");
|
||||
gateway.Requested.ShouldBeEmpty("the folder verdict is decided before any source is read (fail closed)");
|
||||
|
||||
// Positive control: the same session, on the folder it IS granted, gets that folder's Galaxy object.
|
||||
var granted = await ReadAsync(session, Uns(session, EqB), forward: true, page: 0, ct);
|
||||
granted.Status.ShouldBe(StatusCodes.Good);
|
||||
granted.Rows.Select(r => (r.Id, r.SourceNode)).ShouldBe(new (string, string?)[] { ("l-set", Jam), ("l-clear", Jam) });
|
||||
gateway.Requested.ShouldBe(new[] { EqB, "Line3_Conveyor" });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_rebuild_forgets_the_galaxy_sources_until_the_conditions_are_bound_again()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await StartAsync("GalaxyEqHistoryRebuild", encrypted: false, ct);
|
||||
var gateway = new AvevaShapedGateway();
|
||||
rig.Nm.HistorianDataSource = new GatewayHistorianDataSource(gateway, NullLogger<GatewayHistorianDataSource>.Instance);
|
||||
Materialise(rig);
|
||||
rig.Enforce(false, [Key()]);
|
||||
|
||||
// The redeploy re-creates the same conditions and wiring, but (here) binds no Galaxy reference: the folder is back
|
||||
// to its own source alone — a stale binding would keep reading the old objects.
|
||||
rig.Sink.RebuildAddressSpace();
|
||||
Materialise(rig, bind: false);
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: true, ct);
|
||||
var read = await ReadAsync(session, Uns(session, EqA), forward: true, page: 0, ct);
|
||||
|
||||
read.Status.ShouldBe(StatusCodes.GoodNoData);
|
||||
gateway.Requested.ShouldBe(new[] { EqA });
|
||||
}
|
||||
|
||||
/// <summary>Materialises the topology the applier builds from the Galaxy deployment (see the class remarks).</summary>
|
||||
private static void Materialise(ServerEventRig rig, bool bind = true)
|
||||
{
|
||||
rig.Sink.EnsureFolder(OvenFolder, parentNodeId: null, displayName: "Oven7", realm: AddressSpaceRealm.Raw);
|
||||
rig.Sink.EnsureFolder(LineFolder, parentNodeId: null, displayName: "Line3", realm: AddressSpaceRealm.Raw);
|
||||
rig.EnsureEquipment();
|
||||
foreach (var (id, folder, name, reference, equipment) in new[]
|
||||
{
|
||||
(TempHi, OvenFolder, "TempHi", "Oven_007.TempHiAlarm", EqA),
|
||||
(DoorOpen, OvenFolder, "DoorOpen", "OvenDoor_07.DoorAlarm", EqA),
|
||||
(Jam, LineFolder, "Jam", "Line3_Conveyor.JamAlarm", EqB),
|
||||
})
|
||||
{
|
||||
rig.Sink.MaterialiseAlarmCondition(id, folder, name, "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
if (bind) rig.Sink.BindNativeAlarmHistory(id, AddressSpaceRealm.Raw, reference);
|
||||
rig.Sink.WireAlarmNotifiers(id, AddressSpaceRealm.Raw, [equipment], AddressSpaceRealm.Uns);
|
||||
}
|
||||
}
|
||||
|
||||
private static NodeId Uns(ISession session, string id) =>
|
||||
new(id, (ushort)session.NamespaceUris.GetIndex(V3NodeIds.UnsNamespaceUri));
|
||||
|
||||
private static NodeId Raw(ISession session, string id) =>
|
||||
new(id, (ushort)session.NamespaceUris.GetIndex(V3NodeIds.RawNamespaceUri));
|
||||
|
||||
private static async Task<EventRead> ReadAsync(ISession session, NodeId node, bool forward, uint page, CancellationToken ct)
|
||||
{
|
||||
var filter = new EventFilter();
|
||||
foreach (var leaf in new[] { "EventId", "SourceName", "SourceNode", "Severity", "ConditionName" })
|
||||
{
|
||||
var type = leaf == "ConditionName" ? ObjectTypeIds.ConditionType : ObjectTypeIds.BaseEventType;
|
||||
filter.SelectClauses += new SimpleAttributeOperand(type, new QualifiedName(leaf)) { AttributeId = Attributes.Value };
|
||||
}
|
||||
|
||||
var (from, to) = (Epoch.AddMinutes(-1), Epoch.AddMinutes(1));
|
||||
var details = new ReadEventDetails
|
||||
{
|
||||
StartTime = forward ? from : to, EndTime = forward ? to : from, NumValuesPerNode = page, Filter = filter,
|
||||
};
|
||||
var rows = new List<Row>();
|
||||
ByteString point = default;
|
||||
var pages = 0;
|
||||
StatusCode first = StatusCodes.Good;
|
||||
var historyDataIsNull = true;
|
||||
do
|
||||
{
|
||||
var response = await session.HistoryReadAsync(null, new ExtensionObject(details), TimestampsToReturn.Both, false,
|
||||
new HistoryReadValueId[] { new() { NodeId = node, ContinuationPoint = point } }, ct);
|
||||
var result = response.Results.ToList().ShouldHaveSingleItem();
|
||||
if (pages++ == 0) { first = result.StatusCode; historyDataIsNull = result.HistoryData.IsNull; }
|
||||
if (StatusCode.IsBad(result.StatusCode)) break;
|
||||
if (!result.HistoryData.IsNull && ExtensionObject.ToEncodeable(result.HistoryData) is HistoryEvent he)
|
||||
foreach (var e in he.Events.ToList())
|
||||
{
|
||||
var f = e.EventFields.ToList();
|
||||
rows.Add(new Row(
|
||||
System.Text.Encoding.UTF8.GetString(f[0].GetByteString().Span),
|
||||
f[1].GetString(),
|
||||
f[2].IsNull ? null : f[2].GetNodeId().IdentifierAsString,
|
||||
f[3].GetUInt16(),
|
||||
f[4].IsNull ? null : f[4].GetString()));
|
||||
}
|
||||
|
||||
point = result.ContinuationPoint;
|
||||
} while (!point.IsEmpty && pages < 60);
|
||||
|
||||
return new EventRead(first, historyDataIsNull, rows, pages);
|
||||
}
|
||||
|
||||
private sealed record AvevaRow(string Id, string Source, string Object, string Type, int Second, int Priority, string? ConditionVariable);
|
||||
|
||||
private sealed record Row(string Id, string? Source, string? SourceNode, ushort Severity, string? ConditionName);
|
||||
|
||||
private sealed record EventRead(StatusCode Status, bool HistoryDataIsNull, List<Row> Rows, int Pages);
|
||||
|
||||
/// <summary>
|
||||
/// A deterministic gateway answering ReadEvents with AVEVA-shaped rows — <c>SourceName</c> =
|
||||
/// <c>Source_ProcessVariable</c> and lower-case properties as vd03's HistorianGateway returns them — filtered loosely
|
||||
/// on <c>source_object</c>, in event-time order with no intra-timestamp order guarantee (here: storage order).
|
||||
/// </summary>
|
||||
private sealed class AvevaShapedGateway : IHistorianGatewayClient
|
||||
{
|
||||
private readonly List<string?> _requested = [];
|
||||
private readonly List<string> _yielded = [];
|
||||
|
||||
public IReadOnlyList<string?> Requested { get { lock (_requested) return _requested.ToList(); } }
|
||||
|
||||
public IReadOnlyList<string> Yielded { get { lock (_yielded) return _yielded.ToList(); } }
|
||||
|
||||
public async IAsyncEnumerable<HistorianEvent> ReadEventsAsync(
|
||||
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, [EnumeratorCancellation] CancellationToken ct)
|
||||
{
|
||||
lock (_requested) _requested.Add(sourceName);
|
||||
await Task.Yield();
|
||||
foreach (var s in Stored.OrderBy(s => s.Second))
|
||||
{
|
||||
var at = Epoch.AddSeconds(s.Second);
|
||||
if (at < startUtc || at > endUtc) continue; // the gateway's end is inclusive
|
||||
if (sourceName is not null && !s.Object.StartsWith(sourceName, StringComparison.Ordinal)) continue;
|
||||
lock (_yielded) _yielded.Add(s.Id);
|
||||
var ts = Timestamp.FromDateTime(at);
|
||||
var e = new HistorianEvent
|
||||
{
|
||||
Id = s.Id, SourceName = s.Source, Type = s.Type, Namespace = "Application Server", EventTime = ts, ReceivedTime = ts,
|
||||
};
|
||||
e.Properties["source_object"] = s.Object;
|
||||
e.Properties["source_processvariable"] = s.Source;
|
||||
e.Properties["priority"] = s.Priority.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
e.Properties["severity"] = s.ConditionVariable is null ? "0" : "2"; // AVEVA's own scale: never used
|
||||
if (s.ConditionVariable is not null)
|
||||
{
|
||||
e.Properties["source_conditionvariable"] = s.ConditionVariable;
|
||||
e.Properties["alarm_id"] = $"guid-{s.ConditionVariable.ToLowerInvariant()}";
|
||||
}
|
||||
|
||||
yield return e;
|
||||
}
|
||||
}
|
||||
|
||||
public Task<bool> TagExistsAsync(string tag, CancellationToken ct) => throw new NotSupportedException();
|
||||
public IAsyncEnumerable<HistorianSample> ReadRawAsync(string tag, DateTime startUtc, DateTime endUtc, int maxValues, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
public IAsyncEnumerable<HistorianAggregateSample> ReadAggregateAsync(string tag, DateTime startUtc, DateTime endUtc,
|
||||
RetrievalMode mode, TimeSpan interval, CancellationToken ct) => throw new NotSupportedException();
|
||||
public Task<IReadOnlyList<HistorianSample>> ReadAtTimeAsync(string tag, IReadOnlyList<DateTime> timestampsUtc, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
public Task<WriteAck> WriteLiveValuesAsync(string tag, IReadOnlyList<HistorianLiveValue> values, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
public Task<WriteAck> SendEventAsync(HistorianEvent evt, CancellationToken ct) => throw new NotSupportedException();
|
||||
public Task<TagOperationResults> EnsureTagsAsync(IReadOnlyList<HistorianTagDefinition> definitions, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
public Task<bool> ProbeAsync(CancellationToken ct) => Task.FromResult(true);
|
||||
public Task<ConnectionStatus> GetConnectionStatusAsync(CancellationToken ct) => Task.FromResult(new ConnectionStatus());
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,38 @@ public sealed class AddressSpaceApplierRawUnsTests
|
||||
w.FolderNodeIds.ShouldBe(new[] { "EQ-1", "EQ-2" }, ignoreOrder: true);
|
||||
}
|
||||
|
||||
/// <summary>Gitea #886: a native Galaxy alarm's AVEVA reference reaches the sink, bound to its condition after the
|
||||
/// condition is materialised and before its notifiers are wired; a native alarm with no reference binds nothing.</summary>
|
||||
[Fact]
|
||||
public void MaterialiseRawSubtree_binds_a_galaxy_alarms_aveva_reference_to_its_condition()
|
||||
{
|
||||
var sink = new RealmRecordingSink();
|
||||
var composition = new AddressSpaceComposition(
|
||||
new[] { new UnsAreaProjection("a1", "filling") },
|
||||
new[] { new UnsLineProjection("l1", "a1", "line1") },
|
||||
new[] { new EquipmentNode("EQ-1", "station1", "l1") },
|
||||
Array.Empty<DriverInstancePlan>(),
|
||||
Array.Empty<ScriptedAlarmPlan>())
|
||||
{
|
||||
RawTags = new[]
|
||||
{
|
||||
new RawTagPlan("t1", "Plant/Galaxy/Oven7/TempHi", "Plant/Galaxy/Oven7", "drv-gx", "TempHi", "Boolean",
|
||||
Writable: false, Alarm: new EquipmentTagAlarmInfo("LimitAlarm", 700),
|
||||
ReferencingEquipmentPaths: new[] { "filling/line1/station1" },
|
||||
NativeAlarmReference: "Oven_007.TempHiAlarm"),
|
||||
new RawTagPlan("t2", "Plant/Modbus/plc/Hi", "Plant/Modbus/plc", "drv-mb", "Hi", "Boolean",
|
||||
Writable: false, Alarm: new EquipmentTagAlarmInfo("OffNormalAlarm", 500),
|
||||
ReferencingEquipmentPaths: Array.Empty<string>()),
|
||||
},
|
||||
};
|
||||
|
||||
NewApplier(sink).MaterialiseRawSubtree(composition);
|
||||
|
||||
sink.HistoryBindings.ShouldBe(new[] { ("Plant/Galaxy/Oven7/TempHi", AddressSpaceRealm.Raw, "Oven_007.TempHiAlarm") });
|
||||
sink.Calls.ShouldBe(new[] { "condition:Plant/Galaxy/Oven7/TempHi", "bind:Plant/Galaxy/Oven7/TempHi",
|
||||
"wire:Plant/Galaxy/Oven7/TempHi", "condition:Plant/Modbus/plc/Hi" });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Wave C review M2 — composer↔applier PATH-AGREEMENT (the tripwire for the latent DisplayName==Name
|
||||
/// coupling). The composer builds a native alarm's <c>ReferencingEquipmentPaths</c> from the
|
||||
@@ -489,11 +521,26 @@ public sealed class AddressSpaceApplierRawUnsTests
|
||||
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false)
|
||||
=> Variables.Add((variableNodeId, parentFolderNodeId, writable, historianTagname, realm, isArray, arrayLength));
|
||||
|
||||
public List<(string AlarmNodeId, AddressSpaceRealm AlarmRealm, string Reference)> HistoryBindings { get; } = new();
|
||||
public List<string> Calls { get; } = new();
|
||||
|
||||
public void MaterialiseAlarmCondition(string alarmNodeId, string equipmentNodeId, string displayName, string alarmType, int severity, AddressSpaceRealm realm, bool isNative = false)
|
||||
=> Conditions.Add((alarmNodeId, equipmentNodeId, isNative, realm));
|
||||
{
|
||||
Conditions.Add((alarmNodeId, equipmentNodeId, isNative, realm));
|
||||
Calls.Add($"condition:{alarmNodeId}");
|
||||
}
|
||||
|
||||
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm)
|
||||
=> NotifierWirings.Add((alarmNodeId, alarmRealm, notifierFolderNodeIds, notifierFolderRealm));
|
||||
{
|
||||
NotifierWirings.Add((alarmNodeId, alarmRealm, notifierFolderNodeIds, notifierFolderRealm));
|
||||
Calls.Add($"wire:{alarmNodeId}");
|
||||
}
|
||||
|
||||
public void BindNativeAlarmHistory(string alarmNodeId, AddressSpaceRealm alarmRealm, string alarmReference)
|
||||
{
|
||||
HistoryBindings.Add((alarmNodeId, alarmRealm, alarmReference));
|
||||
Calls.Add($"bind:{alarmNodeId}");
|
||||
}
|
||||
|
||||
public void AddReference(string sourceNodeId, AddressSpaceRealm sourceRealm, string targetNodeId, AddressSpaceRealm targetRealm, string referenceType = "Organizes")
|
||||
=> References.Add((sourceNodeId, sourceRealm, targetNodeId, targetRealm, referenceType));
|
||||
|
||||
+36
@@ -316,6 +316,42 @@ public sealed class AddressSpaceComposerDualNamespaceTests
|
||||
c.UnsReferenceVariables.Single(v => v.UnsTagReferenceId == "r3").BackingScalarRefusesArrayValue.ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>Gitea #886: a Galaxy tag that carries an alarm names its AVEVA alarm reference (its <c>attributeRef</c>), so
|
||||
/// the folders its condition fires on can read the history AVEVA stores under that object. A Galaxy value tag, and an
|
||||
/// alarm tag of any other driver (even with an <c>attributeRef</c>-shaped key), name none.</summary>
|
||||
[Fact]
|
||||
public void A_galaxy_alarm_tag_names_its_aveva_alarm_reference_and_no_other_tag_does()
|
||||
{
|
||||
var folder = new RawFolder { RawFolderId = "f", ClusterId = "c1", Name = "Plant" };
|
||||
var gx = new DriverInstance { DriverInstanceId = "drv-gx", ClusterId = "c1", RawFolderId = "f", Name = "Galaxy", DriverType = "GalaxyMxGateway", DriverConfig = "{}" };
|
||||
var mb = new DriverInstance { DriverInstanceId = "drv-mb", ClusterId = "c1", RawFolderId = "f", Name = "Mb", DriverType = "Modbus", DriverConfig = "{}" };
|
||||
var oven = new Device { DeviceId = "d-gx", DriverInstanceId = "drv-gx", Name = "Oven7", DeviceConfig = "{}" };
|
||||
var plc = new Device { DeviceId = "d-mb", DriverInstanceId = "drv-mb", Name = "plc", DeviceConfig = "{}" };
|
||||
const string alarm = "\"alarm\":{\"alarmType\":\"LimitAlarm\",\"severity\":700}";
|
||||
var tags = new[]
|
||||
{
|
||||
new Tag { TagId = "t-hi", DeviceId = "d-gx", Name = "TempHi", DataType = "Boolean", AccessLevel = TagAccessLevel.Read,
|
||||
TagConfig = $"{{\"attributeRef\":\"Oven_007.TempHiAlarm\",{alarm}}}" },
|
||||
new Tag { TagId = "t-temp", DeviceId = "d-gx", Name = "Temp", DataType = "Float", AccessLevel = TagAccessLevel.Read,
|
||||
TagConfig = "{\"attributeRef\":\"Oven_007.Temp\"}" },
|
||||
new Tag { TagId = "t-mb", DeviceId = "d-mb", Name = "Hi", DataType = "Boolean", AccessLevel = TagAccessLevel.Read,
|
||||
TagConfig = $"{{\"region\":\"Coils\",\"address\":0,\"dataType\":\"Bool\",\"attributeRef\":\"Oven_007.X\",{alarm}}}" },
|
||||
};
|
||||
|
||||
var c = AddressSpaceComposer.Compose(
|
||||
Array.Empty<UnsArea>(), Array.Empty<UnsLine>(), Array.Empty<Equipment>(), new[] { gx, mb }, Array.Empty<ScriptedAlarm>(),
|
||||
tags: tags, rawFolders: new[] { folder }, devices: new[] { oven, plc });
|
||||
|
||||
c.RawTags.Single(t => t.TagId == "t-hi").NativeAlarmReference.ShouldBe("Oven_007.TempHiAlarm");
|
||||
c.RawTags.Single(t => t.TagId == "t-temp").NativeAlarmReference.ShouldBeNull();
|
||||
c.RawTags.Single(t => t.TagId == "t-mb").Alarm.ShouldNotBeNull();
|
||||
c.RawTags.Single(t => t.TagId == "t-mb").NativeAlarmReference.ShouldBeNull();
|
||||
|
||||
// The reference is part of the plan's identity: a re-pointed attributeRef is a change, not a no-op redeploy.
|
||||
var hi = c.RawTags.Single(t => t.TagId == "t-hi");
|
||||
hi.Equals(hi with { NativeAlarmReference = "Oven_008.TempHiAlarm" }).ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>#610 review MINOR-1 — the composer hands the table the owning driver's <c>DriverConfig</c> AND the
|
||||
/// tag's own device's <c>DeviceConfig</c>, so a Modbus write cap configured at either level keeps an array that
|
||||
/// can never fit read-only — on the raw node and its UNS mirror alike. The same tag under an uncapped device is
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using HistorianRead = ZB.MOM.WW.OtOpcUa.Core.Abstractions.HistoryReadResult;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #886 — a folder's several event sources read as one: merged in <c>(EventTimeUtc, EventId)</c> order, the cap
|
||||
/// applied to the merge, and "more" never claimed for a stretch a truncated source has not read yet.
|
||||
/// </summary>
|
||||
public sealed class EventSourceFanOutTests
|
||||
{
|
||||
private static readonly DateTime T0 = new(2026, 11, 12, 10, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
private static HistoricalEvent Ev(string id, string source, int second) =>
|
||||
new(id, source, T0.AddSeconds(second), T0.AddSeconds(second), null, 1);
|
||||
|
||||
[Fact]
|
||||
public async Task One_source_is_read_straight_through()
|
||||
{
|
||||
var backend = new StoredEvents(("A", Ev("a1", "A", 1)), ("A", Ev("a2", "A", 2)));
|
||||
|
||||
var r = await EventSourceFanOut.ReadAsync(backend, ["A"], T0, T0.AddMinutes(1), 10, reverse: false, TestContext.Current.CancellationToken);
|
||||
|
||||
r.Events.Select(e => e.EventId).ShouldBe(["a1", "a2"]);
|
||||
backend.Requests.ShouldBe(["A"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Two_sources_merge_in_time_then_source_then_arrival_order_and_drop_a_duplicate()
|
||||
{
|
||||
// Ties keep each source's own order (z-tie before y-tie: A's arrival), and A's before B's (list order) — never
|
||||
// re-sorted by EventId, which could move an unread tie in front of one already sent.
|
||||
var backend = new StoredEvents(
|
||||
("A", Ev("a1", "A", 1)), ("A", Ev("a3", "A.X", 3)), ("A", Ev("z-tie", "A", 5)), ("A", Ev("y-tie", "A", 5)),
|
||||
("B", Ev("b2", "B.Y", 2)), ("B", Ev("a-tie", "B", 5)), ("B", Ev("a1", "A", 1)));
|
||||
|
||||
var r = await EventSourceFanOut.ReadAsync(backend, ["A", "B"], T0, T0.AddMinutes(1), 10, reverse: false, TestContext.Current.CancellationToken);
|
||||
|
||||
r.Events.Select(e => e.EventId).ShouldBe(["a1", "b2", "a3", "z-tie", "y-tie", "a-tie"]);
|
||||
r.ContinuationPoint.ShouldBeNull();
|
||||
backend.Requests.ShouldBe(["A", "B"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_reverse_read_is_the_forward_merge_backwards()
|
||||
{
|
||||
var backend = new StoredEvents(
|
||||
("A", Ev("a1", "A", 1)), ("A", Ev("z-tie", "A", 5)), ("A", Ev("y-tie", "A", 5)),
|
||||
("B", Ev("b2", "B", 2)), ("B", Ev("a-tie", "B", 5)));
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
var forward = await EventSourceFanOut.ReadAsync(backend, ["A", "B"], T0, T0.AddMinutes(1), 10, reverse: false, ct);
|
||||
var reverse = await EventSourceFanOut.ReadAsync(backend, ["A", "B"], T0.AddMinutes(1), T0, 10, reverse: true, ct);
|
||||
|
||||
// What the server's tie-cluster over-fetch relies on: a forward read of a cluster, reversed, is the reverse order.
|
||||
reverse.Events.Select(e => e.EventId).ShouldBe(forward.Events.Select(e => e.EventId).Reverse());
|
||||
reverse.Events.Select(e => e.EventId).ShouldBe(["a-tie", "y-tie", "z-tie", "b2", "a1"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_cap_applies_to_the_merge_and_flags_more()
|
||||
{
|
||||
var backend = new StoredEvents(("A", Ev("a1", "A", 1)), ("A", Ev("a3", "A", 3)), ("B", Ev("b2", "B", 2)));
|
||||
|
||||
var r = await EventSourceFanOut.ReadAsync(backend, ["A", "B"], T0, T0.AddMinutes(1), 2, reverse: false, TestContext.Current.CancellationToken);
|
||||
|
||||
r.Events.Select(e => e.EventId).ShouldBe(["a1", "b2"]);
|
||||
r.ContinuationPoint.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_truncated_source_bounds_the_page_at_the_time_it_stopped()
|
||||
{
|
||||
// A default-capped read (maxEvents 0): A stops after two of its three events (at 2); B returns all of its own.
|
||||
// Unbounded, the page would run on to b4 although A's a3 (at 3) is still unread, so the next page would start
|
||||
// after it. The page ends at A's stop, with B's tie at 2 left out because it follows A's (unread) ties there.
|
||||
var backend = new StoredEvents(
|
||||
("A", Ev("a1", "A", 1)), ("A", Ev("a2", "A", 2)), ("A", Ev("a3", "A", 3)),
|
||||
("B", Ev("b2", "B", 2)), ("B", Ev("b4", "B", 4)))
|
||||
{ DefaultCaps = { ["A"] = 2 } };
|
||||
|
||||
var r = await EventSourceFanOut.ReadAsync(backend, ["A", "B"], T0, T0.AddMinutes(1), 0, reverse: false, TestContext.Current.CancellationToken);
|
||||
|
||||
r.Events.Select(e => e.EventId).ShouldBe(["a1", "a2"]);
|
||||
r.ContinuationPoint.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task At_the_bound_a_complete_source_ahead_of_the_truncated_one_keeps_its_ties()
|
||||
{
|
||||
var backend = new StoredEvents(
|
||||
("A", Ev("a1", "A", 1)), ("A", Ev("a2", "A", 2)), ("A", Ev("a3", "A", 3)),
|
||||
("B", Ev("b2", "B", 2)), ("B", Ev("b4", "B", 4)))
|
||||
{ DefaultCaps = { ["A"] = 2 } };
|
||||
|
||||
// B is listed first, so at 2 its tie precedes A's in merge order and is complete: it stays.
|
||||
var r = await EventSourceFanOut.ReadAsync(backend, ["B", "A"], T0, T0.AddMinutes(1), 0, reverse: false, TestContext.Current.CancellationToken);
|
||||
|
||||
r.Events.Select(e => e.EventId).ShouldBe(["a1", "b2", "a2"]);
|
||||
r.ContinuationPoint.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_truncated_source_bounds_a_reverse_page_at_the_oldest_time_it_returned()
|
||||
{
|
||||
var backend = new StoredEvents(
|
||||
("A", Ev("a3", "A", 3)), ("A", Ev("a4", "A", 4)), ("A", Ev("a5", "A", 5)),
|
||||
("B", Ev("b4", "B", 4)), ("B", Ev("b1", "B", 1)))
|
||||
{ DefaultCaps = { ["A"] = 2 } };
|
||||
|
||||
var r = await EventSourceFanOut.ReadAsync(backend, ["A", "B"], T0.AddMinutes(1), T0, 0, reverse: true, TestContext.Current.CancellationToken);
|
||||
|
||||
// A returned 5, 4 and stopped at 4. Reverse merge order at 4 visits B (listed later) first, then A: b4 is
|
||||
// complete and kept, A's a4 closes the page, and b1 (older than A's unread a3) is left for the next page.
|
||||
r.Events.Select(e => e.EventId).ShouldBe(["a5", "b4", "a4"]);
|
||||
r.ContinuationPoint.ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Paging_the_merge_from_each_last_event_walks_every_event_once()
|
||||
{
|
||||
// The server's resume rule: read again from the last event's time INCLUSIVE and skip the ties already sent.
|
||||
var stored = new List<(string, HistoricalEvent)>();
|
||||
for (var i = 0; i < 9; i++) stored.Add(("A", Ev($"a{i}", "A", i)));
|
||||
for (var i = 0; i < 9; i += 2) stored.Add(("B", Ev($"b{i}", "B.X", i)));
|
||||
stored.Add(("B", Ev("b-tie", "B", 4)));
|
||||
var backend = new StoredEvents([.. stored]);
|
||||
var whole = (await EventSourceFanOut.ReadAsync(backend, ["A", "B"], T0, T0.AddMinutes(1), 100, false, TestContext.Current.CancellationToken))
|
||||
.Events.Select(e => e.EventId).ToList();
|
||||
|
||||
foreach (var cap in new[] { 1, 2, 3, 5 })
|
||||
{
|
||||
var got = new List<string>();
|
||||
var start = T0;
|
||||
var skip = 0;
|
||||
for (var guard = 0; guard < 100; guard++)
|
||||
{
|
||||
var page = await EventSourceFanOut.ReadAsync(backend, ["A", "B"], start, T0.AddMinutes(1), cap + skip, false, TestContext.Current.CancellationToken);
|
||||
var events = page.Events.SkipWhile((e, i) => i < skip && e.EventTimeUtc == start).Take(cap).ToList();
|
||||
got.AddRange(events.Select(e => e.EventId));
|
||||
var more = page.ContinuationPoint is not null || page.Events.Count - Math.Min(skip, page.Events.Count) > cap;
|
||||
if (!more) break;
|
||||
if (events.Count == 0) { skip += cap; continue; }
|
||||
var boundary = events[^1].EventTimeUtc;
|
||||
var trailing = events.AsEnumerable().Reverse().TakeWhile(e => e.EventTimeUtc == boundary).Count();
|
||||
skip = boundary == start ? skip + trailing : trailing;
|
||||
start = boundary;
|
||||
}
|
||||
|
||||
got.ShouldBe(whole, $"cap {cap}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A backend holding events per source; a read returns that source's events in the window, forward or reverse,
|
||||
/// cut to the cap with a continuation point when more remain.</summary>
|
||||
private sealed class StoredEvents(params (string Source, HistoricalEvent Event)[] stored) : IHistorianDataSource
|
||||
{
|
||||
public List<string?> Requests { get; } = [];
|
||||
|
||||
/// <summary>A source's own cap for a default-capped read (maxEvents <= 0); uncapped when absent.</summary>
|
||||
public Dictionary<string, int> DefaultCaps { get; } = [];
|
||||
|
||||
public bool SupportsReverseEvents => true;
|
||||
|
||||
public Task<HistoricalEventsResult> ReadEventsAsync(
|
||||
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, bool reverse, CancellationToken cancellationToken)
|
||||
{
|
||||
Requests.Add(sourceName);
|
||||
var (lo, hi) = reverse ? (endUtc, startUtc) : (startUtc, endUtc);
|
||||
var rows = stored.Where(s => s.Source == sourceName)
|
||||
.Select(s => s.Event)
|
||||
.Where(e => reverse ? e.EventTimeUtc > lo && e.EventTimeUtc <= hi : e.EventTimeUtc >= lo && e.EventTimeUtc < hi)
|
||||
.OrderBy(e => e.EventTimeUtc) // stable: ties keep storage order, as the gateway's do
|
||||
.ToList();
|
||||
if (reverse) rows.Reverse();
|
||||
var cap = maxEvents > 0 ? maxEvents : DefaultCaps.GetValueOrDefault(sourceName ?? string.Empty, 0);
|
||||
var more = cap > 0 && rows.Count > cap;
|
||||
return Task.FromResult(new HistoricalEventsResult(more ? rows.Take(cap).ToList() : rows, more ? [0x01] : null));
|
||||
}
|
||||
|
||||
public Task<HistoricalEventsResult> ReadEventsAsync(
|
||||
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents, CancellationToken cancellationToken) =>
|
||||
ReadEventsAsync(sourceName, startUtc, endUtc, maxEvents, reverse: false, cancellationToken);
|
||||
|
||||
public Task<HistorianRead> ReadRawAsync(string fullReference, DateTime startUtc, DateTime endUtc, uint maxValuesPerNode,
|
||||
CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
|
||||
public Task<HistorianRead> ReadProcessedAsync(string fullReference, DateTime startUtc, DateTime endUtc, TimeSpan interval,
|
||||
HistoryAggregateType aggregate, CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
|
||||
public Task<HistorianRead> ReadAtTimeAsync(string fullReference, IReadOnlyList<DateTime> timestampsUtc,
|
||||
CancellationToken cancellationToken) => throw new NotSupportedException();
|
||||
|
||||
public HistorianHealthSnapshot GetHealthSnapshot() => NullHistorianDataSource.Instance.GetHealthSnapshot();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user