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:
@@ -918,8 +918,15 @@ public sealed class AddressSpaceApplier
|
||||
if (!SafeMaterialiseAlarmCondition(t.NodeId, t.ParentNodeId ?? string.Empty, t.Name, t.Alarm.AlarmType, t.Alarm.Severity, isNative: true, AddressSpaceRealm.Raw))
|
||||
{
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
else if (t.ReferencingEquipmentPaths.Count > 0)
|
||||
|
||||
// #886: a Galaxy alarm's AVEVA reference, so every folder this condition fires on also reads the
|
||||
// history AVEVA stores under its object. Bound before the wiring; the folders are read at HistoryRead.
|
||||
if (t.NativeAlarmReference is { } nativeReference && !SafeBindNativeAlarmHistory(t.NodeId, nativeReference))
|
||||
failed++;
|
||||
|
||||
if (t.ReferencingEquipmentPaths.Count > 0)
|
||||
{
|
||||
// Multi-notifier fan-out: wire the SINGLE condition as an event notifier of each
|
||||
// referencing equipment's UNS folder, so one ReportEvent reaches every referencing equipment
|
||||
@@ -1247,6 +1254,12 @@ public sealed class AddressSpaceApplier
|
||||
/// swallowing (and Warning-logging) any sink fault. Returns <c>true</c> on success, <c>false</c> when the
|
||||
/// sink threw — callers tally the false into their pass's failed-node count (archreview 01/S-1).</summary>
|
||||
/// <returns><c>true</c> when the notifiers were wired; <c>false</c> when the sink threw.</returns>
|
||||
private bool SafeBindNativeAlarmHistory(string alarmNodeId, string alarmReference)
|
||||
{
|
||||
try { _sink.BindNativeAlarmHistory(alarmNodeId, AddressSpaceRealm.Raw, alarmReference); return true; }
|
||||
catch (Exception ex) { _logger.LogWarning(ex, "AddressSpaceApplier: BindNativeAlarmHistory threw for {Node}", alarmNodeId); return false; }
|
||||
}
|
||||
|
||||
private bool SafeWireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm)
|
||||
{
|
||||
try { _sink.WireAlarmNotifiers(alarmNodeId, alarmRealm, notifierFolderNodeIds, notifierFolderRealm); return true; }
|
||||
|
||||
@@ -150,6 +150,11 @@ public sealed record RawContainerNode(
|
||||
/// the DRIVER, deliberately not gated on <see cref="IsArray"/>, so a surgical scalar↔array edit does not
|
||||
/// flip it. It is not in the classifier's surgical whitelist, so a change to it (a driver's type edited in
|
||||
/// place) rebuilds.
|
||||
/// <see cref="NativeAlarmReference"/> is the Galaxy alarm reference (<c>tag_name.AlarmAttribute</c>, the tag's
|
||||
/// <c>attributeRef</c>) of a <see cref="DriverTypeNames.Galaxy"/> tag that carries an <see cref="Alarm"/>, and null for
|
||||
/// every other tag. AVEVA stores the alarm's history under that reference's object, so the node manager adds the
|
||||
/// object to the event-history sources of every folder the condition fires on (Gitea #886). It is not in the
|
||||
/// surgical whitelist either: an alarm-bearing tag's delta rebuilds anyway.
|
||||
/// <para><b>ADDING A FIELD IS A FOUR-PLACE CONTRACT — the hand-written equality below does NOT close
|
||||
/// over new members.</b> Because <see cref="ReferencingEquipmentPaths"/> forces a custom
|
||||
/// <c>Equals</c>/<c>GetHashCode</c>, the compiler's positional equality is suppressed, so a field added
|
||||
@@ -178,7 +183,8 @@ public sealed record RawTagPlan(
|
||||
uint? ArrayLength = null,
|
||||
AddressSpaceRealm Realm = AddressSpaceRealm.Raw,
|
||||
bool ArrayWritable = false,
|
||||
bool ScalarRefusesArrayValue = false)
|
||||
bool ScalarRefusesArrayValue = false,
|
||||
string? NativeAlarmReference = null)
|
||||
{
|
||||
/// <inheritdoc />
|
||||
// Structural equality: the auto-generated record equality compares ReferencingEquipmentPaths (an
|
||||
@@ -202,6 +208,7 @@ public sealed record RawTagPlan(
|
||||
Realm == other.Realm &&
|
||||
ArrayWritable == other.ArrayWritable &&
|
||||
ScalarRefusesArrayValue == other.ScalarRefusesArrayValue &&
|
||||
NativeAlarmReference == other.NativeAlarmReference &&
|
||||
ReferencingEquipmentPaths.SequenceEqual(other.ReferencingEquipmentPaths, StringComparer.Ordinal);
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -211,7 +218,7 @@ public sealed record RawTagPlan(
|
||||
hash.Add(TagId); hash.Add(NodeId); hash.Add(ParentNodeId); hash.Add(DriverInstanceId);
|
||||
hash.Add(Name); hash.Add(DataType); hash.Add(Writable); hash.Add(Alarm);
|
||||
hash.Add(IsHistorized); hash.Add(HistorianTagname); hash.Add(IsArray); hash.Add(ArrayLength);
|
||||
hash.Add(Realm); hash.Add(ArrayWritable); hash.Add(ScalarRefusesArrayValue);
|
||||
hash.Add(Realm); hash.Add(ArrayWritable); hash.Add(ScalarRefusesArrayValue); hash.Add(NativeAlarmReference);
|
||||
foreach (var p in ReferencingEquipmentPaths) hash.Add(p, StringComparer.Ordinal);
|
||||
return hash.ToHashCode();
|
||||
}
|
||||
@@ -803,6 +810,7 @@ public static class AddressSpaceComposer
|
||||
var equipPathByTag = BuildReferencingEquipmentPathsByTag(unsTagReferences, unsAreas, unsLines, equipment);
|
||||
var arrayWritableFor = BuildArrayWriteCapability(driverInstances, devices);
|
||||
var scalarRefusesArrayFor = BuildScalarArrayRefusal(driverInstances, devices);
|
||||
var nativeAlarmReferenceFor = BuildNativeAlarmReference(driverInstances, devices);
|
||||
|
||||
var rawTags = new List<RawTagPlan>();
|
||||
foreach (var t in tags ?? Array.Empty<Tag>())
|
||||
@@ -820,6 +828,8 @@ public static class AddressSpaceComposer
|
||||
? new EquipmentTagAlarmInfo(a.AlarmType, a.Severity, a.HistorizeToAveva)
|
||||
: null;
|
||||
var refEquipPaths = equipPathByTag.GetValueOrDefault(t.TagId, Array.Empty<string>());
|
||||
// #886: the AVEVA history source of a native Galaxy alarm (null for every other tag).
|
||||
var nativeAlarmReference = alarm is null ? null : nativeAlarmReferenceFor(t);
|
||||
|
||||
rawTags.Add(new RawTagPlan(
|
||||
TagId: t.TagId,
|
||||
@@ -836,7 +846,8 @@ public static class AddressSpaceComposer
|
||||
IsArray: intent.IsArray,
|
||||
ArrayLength: intent.ArrayLength,
|
||||
ArrayWritable: arrayWritable,
|
||||
ScalarRefusesArrayValue: scalarRefusesArray));
|
||||
ScalarRefusesArrayValue: scalarRefusesArray,
|
||||
NativeAlarmReference: nativeAlarmReference));
|
||||
}
|
||||
|
||||
containers.Sort((x, y) => string.CompareOrdinal(x.NodeId, y.NodeId));
|
||||
@@ -876,6 +887,17 @@ public static class AddressSpaceComposer
|
||||
return tag => DriverArrayWriteSupport.RefusesArrayValueOnScalarTag(resolve(tag).Driver?.DriverType);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A tag's Galaxy alarm reference (its <c>attributeRef</c>) when its driver is the Galaxy driver, else null — read
|
||||
/// with the driver's own parser (<see cref="GalaxyAttributeRef"/>), so a tag the driver cannot dial names no source.
|
||||
/// </summary>
|
||||
private static Func<Tag, string?> BuildNativeAlarmReference(
|
||||
IReadOnlyList<DriverInstance> driverInstances, IReadOnlyList<Device>? devices)
|
||||
{
|
||||
var resolve = BuildTagOwnerResolver(driverInstances, devices);
|
||||
return tag => GalaxyAttributeRef.AlarmReferenceOf(resolve(tag).Driver?.DriverType, tag.TagConfig);
|
||||
}
|
||||
|
||||
// Tag → (owning driver, owning device); first row wins on a duplicate id, matching the composer's other id maps.
|
||||
private static Func<Tag, (DriverInstance? Driver, Device? Device)> BuildTagOwnerResolver(
|
||||
IReadOnlyList<DriverInstance> driverInstances, IReadOnlyList<Device>? devices)
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
/// <summary>A native condition an AVEVA history row can resolve to (Gitea #886).</summary>
|
||||
/// <param name="AlarmId">The condition's id (its RawPath), from which the server resolves the row's <c>SourceNode</c>.</param>
|
||||
/// <param name="ConditionName">The live condition's <c>ConditionName</c>.</param>
|
||||
internal sealed record EventHistoryCondition(string AlarmId, string ConditionName);
|
||||
|
||||
/// <summary>
|
||||
/// What one notifier folder's event history reads (Gitea #886): its event sources, and the native conditions that fire
|
||||
/// on it live keyed by their Galaxy alarm reference.
|
||||
/// </summary>
|
||||
internal sealed class EventHistoryScope
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, EventHistoryCondition> NoConditions =
|
||||
new Dictionary<string, EventHistoryCondition>();
|
||||
|
||||
private readonly IReadOnlyDictionary<string, EventHistoryCondition> _conditions;
|
||||
|
||||
private EventHistoryScope(IReadOnlyList<string> sources, IReadOnlyDictionary<string, EventHistoryCondition> conditions)
|
||||
{
|
||||
Sources = sources;
|
||||
_conditions = conditions;
|
||||
// One source keeps its bare name, so a pre-#886 folder's cursor is exactly what it was.
|
||||
CursorKey = string.Join('\n', sources);
|
||||
}
|
||||
|
||||
/// <summary>The sources to read: distinct, ordinal-sorted (the folder's own first when it is the only one).</summary>
|
||||
public IReadOnlyList<string> Sources { get; }
|
||||
|
||||
/// <summary>The identity a continuation point is bound to: the whole source set.</summary>
|
||||
public string CursorKey { get; }
|
||||
|
||||
/// <summary>A scope of one source and no Galaxy conditions (every non-Galaxy folder).</summary>
|
||||
/// <param name="source">The folder's own source.</param>
|
||||
/// <returns>The scope.</returns>
|
||||
public static EventHistoryScope Single(string source) => new([source], NoConditions);
|
||||
|
||||
/// <summary>A folder's own source plus the Galaxy objects behind it.</summary>
|
||||
/// <param name="ownSource">The folder's own source.</param>
|
||||
/// <param name="objects">The Galaxy objects of the native conditions that fire on it (duplicates allowed).</param>
|
||||
/// <param name="conditions">Those conditions by Galaxy alarm reference (case-insensitive).</param>
|
||||
/// <returns>The scope.</returns>
|
||||
public static EventHistoryScope Create(
|
||||
string ownSource, IEnumerable<string>? objects, IReadOnlyDictionary<string, EventHistoryCondition> conditions)
|
||||
{
|
||||
var sources = new SortedSet<string>(StringComparer.Ordinal) { ownSource };
|
||||
foreach (var o in objects ?? []) sources.Add(o);
|
||||
return new EventHistoryScope(sources.ToList(), conditions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Give each row whose <see cref="HistoricalEvent.ConditionReference"/> names one of this folder's native conditions
|
||||
/// that condition's id (so its <c>SourceNode</c> resolves) and live <c>ConditionName</c>. Other rows are unchanged.
|
||||
/// </summary>
|
||||
/// <param name="events">A page of events.</param>
|
||||
/// <returns>The page, resolved.</returns>
|
||||
public IReadOnlyList<HistoricalEvent> ResolveConditions(IReadOnlyList<HistoricalEvent> events)
|
||||
{
|
||||
if (_conditions.Count == 0 || events.Count == 0) return events;
|
||||
List<HistoricalEvent>? resolved = null;
|
||||
for (var i = 0; i < events.Count; i++)
|
||||
{
|
||||
var e = events[i];
|
||||
if (e.ConditionReference is not { } reference || !_conditions.TryGetValue(reference, out var condition)) continue;
|
||||
resolved ??= [.. events];
|
||||
resolved[i] = e with { AlarmId = condition.AlarmId, ConditionName = condition.ConditionName };
|
||||
}
|
||||
|
||||
return resolved ?? events;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads several event sources as one (Gitea #886): one backend read per source (the historiangw <c>ReadEvents</c>
|
||||
/// filter is a single predicate, so there is no multi-source request), merged, de-duplicated by EventId and cut to the
|
||||
/// cap.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Merge order</b> is <c>(EventTimeUtc, source, arrival)</c>: time in the read's direction, then the source's
|
||||
/// position in the folder's (ordinal-sorted) source list — reversed for a reverse read — then the order the source
|
||||
/// returned its events in. A source's own order within a timestamp is all the paging needs to be stable (the
|
||||
/// Gateway orders by event time only), so ties are never re-sorted by EventId here: re-sorting could move an
|
||||
/// unread tie in front of one already sent. The reverse form is the forward form backwards, which is what the
|
||||
/// server's tie-cluster over-fetch (a forward read, reversed) relies on. A walked-back reverse read (Gateway) sorts
|
||||
/// its ties by EventId itself, as before.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Truncation stays honest.</b> A source that flags "more" returned a prefix of its own stream, ending at time H.
|
||||
/// Its unread events lie at H or later (in the read's direction), and at H they follow what it returned. So the
|
||||
/// page keeps every event before the earliest such H, then, at H, each source's events in merge order up to and
|
||||
/// including the first source truncated at H — never an event the unread ones would precede. The page is never
|
||||
/// empty, because that source returned at least one event at H. When every source is read with the same cap (the
|
||||
/// server always passes one) a page cut to that cap already stops there; the bound matters for an uncapped or
|
||||
/// default-capped read.
|
||||
/// </para>
|
||||
/// <para>A single source is passed straight through, so a folder with one source reads exactly as before #886.</para>
|
||||
/// </remarks>
|
||||
internal static class EventSourceFanOut
|
||||
{
|
||||
/// <summary>Reads <paramref name="sources"/> over one window and merges them.</summary>
|
||||
/// <param name="source">The backend.</param>
|
||||
/// <param name="sources">The event sources (at least one).</param>
|
||||
/// <param name="startUtc">The window start (the later bound for a reverse read).</param>
|
||||
/// <param name="endUtc">The window end.</param>
|
||||
/// <param name="maxEvents">The cap, passed to every source; <c><= 0</c> is the backend's default cap.</param>
|
||||
/// <param name="reverse">Newest first.</param>
|
||||
/// <param name="ct">Cancellation.</param>
|
||||
/// <returns>The merged events, and a non-null continuation point when more exist.</returns>
|
||||
public static async Task<HistoricalEventsResult> ReadAsync(
|
||||
IHistorianDataSource source, IReadOnlyList<string> sources, DateTime startUtc, DateTime endUtc, int maxEvents,
|
||||
bool reverse, CancellationToken ct)
|
||||
{
|
||||
if (sources.Count == 1)
|
||||
return await source.ReadEventsAsync(sources[0], startUtc, endUtc, maxEvents, reverse, ct).ConfigureAwait(false);
|
||||
|
||||
var merged = new List<Merged>();
|
||||
var seen = new HashSet<string>(StringComparer.Ordinal);
|
||||
var more = false;
|
||||
// Per source: the time its truncated read ended at, or null when it returned everything it holds.
|
||||
var truncatedAt = new DateTime?[sources.Count];
|
||||
for (var s = 0; s < sources.Count; s++)
|
||||
{
|
||||
// Sequential: the folder's sources share the backend's session pool, and the batch already reads folders in
|
||||
// parallel.
|
||||
var read = await source.ReadEventsAsync(sources[s], startUtc, endUtc, maxEvents, reverse, ct).ConfigureAwait(false);
|
||||
for (var i = 0; i < read.Events.Count; i++)
|
||||
{
|
||||
var e = read.Events[i];
|
||||
if (string.IsNullOrEmpty(e.EventId) || seen.Add(e.EventId)) merged.Add(new Merged(e, s, i));
|
||||
}
|
||||
|
||||
if (read.ContinuationPoint is null) continue;
|
||||
more = true;
|
||||
// A truncated read with no events gives no bound; the cap below still flags the page incomplete.
|
||||
if (read.Events.Count > 0) truncatedAt[s] = read.Events[^1].EventTimeUtc;
|
||||
}
|
||||
|
||||
var order = new MergeOrder(reverse);
|
||||
merged.Sort(order);
|
||||
|
||||
// H: the earliest (in the read's direction) time a truncated source stopped at.
|
||||
DateTime? horizon = null;
|
||||
foreach (var t in truncatedAt)
|
||||
if (t is { } at && (horizon is not { } h || (reverse ? at > h : at < h))) horizon = at;
|
||||
|
||||
var page = new List<HistoricalEvent>(merged.Count);
|
||||
foreach (var m in merged)
|
||||
{
|
||||
if (horizon is { } h)
|
||||
{
|
||||
var t = m.Event.EventTimeUtc;
|
||||
if (reverse ? t < h : t > h) break;
|
||||
// At H, merge order visits whole sources in turn: stop after the first one that was cut there.
|
||||
if (t == h && page.Count > 0 && page[^1].EventTimeUtc == h && StoppedAt(merged, page.Count, h)) break;
|
||||
}
|
||||
|
||||
page.Add(m.Event);
|
||||
}
|
||||
|
||||
if (maxEvents > 0 && page.Count > maxEvents)
|
||||
{
|
||||
page.RemoveRange(maxEvents, page.Count - maxEvents);
|
||||
more = true;
|
||||
}
|
||||
|
||||
return new HistoricalEventsResult(page, more ? [0x01] : null);
|
||||
|
||||
// Whether the event before merged[next] closed a source that was truncated at h (and merged[next] is another source's).
|
||||
bool StoppedAt(List<Merged> all, int next, DateTime h)
|
||||
{
|
||||
var previous = all[next - 1];
|
||||
return previous.Source != all[next].Source && truncatedAt[previous.Source] == h;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One merged event: the event, its source's position in the list, and its position in that source's read.</summary>
|
||||
private readonly record struct Merged(HistoricalEvent Event, int Source, int Arrival);
|
||||
|
||||
/// <summary>Time in the read's direction, then source position (reversed for a reverse read), then arrival.</summary>
|
||||
private sealed class MergeOrder(bool reverse) : IComparer<Merged>
|
||||
{
|
||||
public int Compare(Merged x, Merged y)
|
||||
{
|
||||
var c = x.Event.EventTimeUtc.CompareTo(y.Event.EventTimeUtc);
|
||||
if (c == 0) c = x.Source.CompareTo(y.Source);
|
||||
if (reverse) c = -c;
|
||||
return c != 0 ? c : x.Arrival.CompareTo(y.Arrival);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
/// <see cref="_alarmConditions"/> so a re-materialise as the other kind is correct.</summary>
|
||||
private readonly HashSet<RealmKey> _nativeAlarmNodeIds = new();
|
||||
/// <summary>
|
||||
/// Gitea #886 — native condition key → its Galaxy alarm reference (<c>tag_name.AlarmAttribute</c>), recorded by
|
||||
/// <see cref="BindNativeAlarmHistory"/>. Every folder the condition fires on live reads the history AVEVA stores
|
||||
/// under the reference's object (<see cref="ResolveEventHistoryScope"/>). Guarded by <c>Lock</c>; maintained in
|
||||
/// lock-step with <see cref="_nativeAlarmNodeIds"/> (dropped wherever a condition is, cleared on rebuild).
|
||||
/// </summary>
|
||||
private readonly Dictionary<RealmKey, string> _nativeAlarmReferences = new();
|
||||
/// <summary>
|
||||
/// Gitea #797 — the explicit binding from each LIVE scripted condition to the equipment that owns it.
|
||||
/// A scripted condition's NodeId is its opaque <c>ScriptedAlarmId</c> and cannot be split into an ACL
|
||||
/// scope, so with <c>Security:Acl:Enabled</c> its Part 9 commands are authorized at the owner's scope
|
||||
@@ -2319,6 +2326,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
// H6a: re-materialising the same id as the OTHER kind (native↔scripted) must reflect the new
|
||||
// kind, so always drop the stale native flag first and only re-add it below when isNative.
|
||||
_nativeAlarmNodeIds.Remove(conditionKey);
|
||||
_nativeAlarmReferences.Remove(conditionKey);
|
||||
// Gitea #797: the dropped instance's owner binding goes with it; the new one is bound below.
|
||||
_scriptedAlarmOwners.Remove(conditionKey);
|
||||
|
||||
@@ -2721,6 +2729,21 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IOpcUaAddressSpaceSink.BindNativeAlarmHistory"/>
|
||||
public void BindNativeAlarmHistory(string alarmNodeId, AddressSpaceRealm alarmRealm, string alarmReference)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(alarmNodeId);
|
||||
if (string.IsNullOrWhiteSpace(alarmReference)) return;
|
||||
var key = MapKey(alarmRealm, alarmNodeId);
|
||||
lock (Lock)
|
||||
{
|
||||
// Only a materialised NATIVE condition carries an upstream reference; anything else (a mid-rebuild race, a
|
||||
// scripted id) is a no-op, never a throw — a deploy must not fault on it.
|
||||
if (!_alarmConditions.ContainsKey(key) || !_nativeAlarmNodeIds.Contains(key)) return;
|
||||
_nativeAlarmReferences[key] = alarmReference.Trim();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Tear down (bidirectionally) every notifier wired for the condition at <paramref name="alarmKey"/>
|
||||
/// and drop its tracking entry. MUST be called under <c>Lock</c>. Used on condition-removal + full rebuild
|
||||
/// so no inverse-notifier entry leaks. A no-op when the condition has no wired notifiers.</summary>
|
||||
@@ -4648,6 +4671,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
// H6a: drop the native-alarm flags in lock-step with the conditions they classify, so a
|
||||
// re-materialise on the next apply (possibly as the other kind) starts from a clean slate.
|
||||
_nativeAlarmNodeIds.Clear();
|
||||
_nativeAlarmReferences.Clear();
|
||||
_scriptedAlarmOwners.Clear();
|
||||
|
||||
foreach (var f in _folders.Values) PredefinedNodes?.Remove(f.NodeId);
|
||||
@@ -4812,6 +4836,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
condition.Parent?.RemoveChild(condition);
|
||||
ForgetPredefinedSubtree(condition);
|
||||
_nativeAlarmNodeIds.Remove(key);
|
||||
_nativeAlarmReferences.Remove(key);
|
||||
_scriptedAlarmOwners.Remove(key);
|
||||
LowerAllEventsMonitoring(condition);
|
||||
e = BuildNodesRemovedModelChange(alarmNodeId, realm);
|
||||
@@ -4922,6 +4947,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
if (c.Parent is { } parent && !removedParents.Contains(parent)) parent.RemoveChild(c);
|
||||
ForgetPredefinedSubtree(c);
|
||||
_nativeAlarmNodeIds.Remove(key);
|
||||
_nativeAlarmReferences.Remove(key);
|
||||
_scriptedAlarmOwners.Remove(key);
|
||||
LowerAllEventsMonitoring(c);
|
||||
return;
|
||||
@@ -7830,8 +7856,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
continue;
|
||||
}
|
||||
|
||||
var sn = sourceName;
|
||||
work.Add(() => ServeEventsAsync(handle, sn, details, selectClauses, where, filterContext, nodesToRead, session,
|
||||
// #886: the folder's own source plus the Galaxy objects of the native conditions that fire on it, taken
|
||||
// under Lock now so the whole read (every page source, every SourceNode) sees one membership.
|
||||
var scope = ResolveEventHistoryScope(handle.NodeId, sourceName);
|
||||
work.Add(() => ServeEventsAsync(handle, scope, details, selectClauses, where, filterContext, nodesToRead, session,
|
||||
results, errors, ct));
|
||||
}
|
||||
|
||||
@@ -7839,6 +7867,42 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #886 — what one notifier folder's event history reads: its own registered source (OtOpcUa's own events,
|
||||
/// as before) plus the Galaxy object of every native condition that fires on it live — those parented under it
|
||||
/// and those <see cref="WireAlarmNotifiers"/> wired to it — and those conditions by their Galaxy reference, so an
|
||||
/// AVEVA row resolves to the same condition its live event comes from. Taken under <c>Lock</c>.
|
||||
/// </summary>
|
||||
/// <param name="folderNodeId">The notifier folder.</param>
|
||||
/// <param name="ownSource">The folder's registered event source (its NodeId identifier).</param>
|
||||
/// <returns>The folder's scope; just <paramref name="ownSource"/> when no Galaxy condition fires on it.</returns>
|
||||
private EventHistoryScope ResolveEventHistoryScope(NodeId folderNodeId, string ownSource)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
if (_nativeAlarmReferences.Count == 0 || !_notifierFolders.TryGetValue(folderNodeId, out var folder))
|
||||
return EventHistoryScope.Single(ownSource);
|
||||
|
||||
List<string>? objects = null;
|
||||
Dictionary<string, EventHistoryCondition>? conditions = null;
|
||||
foreach (var (key, reference) in _nativeAlarmReferences)
|
||||
{
|
||||
if (!_alarmConditions.TryGetValue(key, out var alarm)) continue;
|
||||
var firesHere = ReferenceEquals(alarm.Parent, folder)
|
||||
|| (_alarmNotifierWiring.TryGetValue(key, out var wiring)
|
||||
&& ReferenceEquals(wiring.Alarm, alarm) && wiring.Folders.Contains(folder));
|
||||
if (!firesHere) continue;
|
||||
if (GalaxyAttributeRef.ObjectNameOf(reference) is { } objectName) (objects ??= []).Add(objectName);
|
||||
// Galaxy names are case-insensitive, and the driver matches its live alarm references the same way.
|
||||
conditions ??= new Dictionary<string, EventHistoryCondition>(StringComparer.OrdinalIgnoreCase);
|
||||
conditions.TryAdd(reference, new EventHistoryCondition(
|
||||
key.Id, alarm.ConditionName?.Value ?? alarm.DisplayName.Text ?? key.Id));
|
||||
}
|
||||
|
||||
return conditions is null ? EventHistoryScope.Single(ownSource) : EventHistoryScope.Create(ownSource, objects, conditions);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serve one registered event-history notifier handle: reads the source's events over the request
|
||||
/// window, projects them onto the select clauses, and fills the service-level results/errors slots.
|
||||
@@ -7847,7 +7911,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
/// <c>BadTimeout</c>.
|
||||
/// </summary>
|
||||
/// <param name="handle">The notifier node handle; <c>handle.Index</c> indexes results/errors.</param>
|
||||
/// <param name="sourceName">The registered historian event-source name for this notifier.</param>
|
||||
/// <param name="scope">The notifier's event-history sources and the native conditions that fire on it (#886).</param>
|
||||
/// <param name="details">The event-read details (window + count cap).</param>
|
||||
/// <param name="selectClauses">The event-filter select clauses (the fields to emit, in order).</param>
|
||||
/// <param name="where">The event filter's where-clause, or null for none.</param>
|
||||
@@ -7857,7 +7921,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
/// <param name="ct">Per-request deadline token.</param>
|
||||
private async Task ServeEventsAsync(
|
||||
NodeHandle handle,
|
||||
string? sourceName,
|
||||
EventHistoryScope scope,
|
||||
ReadEventDetails details,
|
||||
ArrayOf<SimpleAttributeOperand> selectClauses,
|
||||
ContentFilter? where,
|
||||
@@ -7873,6 +7937,12 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
var resumed = inboundCp is { Length: > 0 };
|
||||
// One snapshot of the (hot-swappable) source for the whole read: the capability check and every call must agree.
|
||||
var source = _historianDataSource;
|
||||
// The folder's sources read as ONE source (#886): a single source is read directly, several are fanned out and
|
||||
// merged in (EventTimeUtc, source, arrival) order (EventSourceFanOut), so the paging below is the same either way.
|
||||
// The cursor is bound to the whole source set.
|
||||
var sourceName = scope.CursorKey;
|
||||
Task<HistoricalEventsResult> ReadSourcesAsync(DateTime from, DateTime to, int max, bool rev, CancellationToken token) =>
|
||||
EventSourceFanOut.ReadAsync(source, scope.Sources, from, to, max, rev, token);
|
||||
try
|
||||
{
|
||||
var startUtc = SdkValueBoundary.ToClrTimestamp(details.StartTime);
|
||||
@@ -7888,14 +7958,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
// for THIS node only.
|
||||
var state = _historyContinuationStore.TryTake(session, inboundCp.ToArray());
|
||||
// A point is bound to the node that issued it: another node's source name is a miss too.
|
||||
if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != (sourceName ?? string.Empty))
|
||||
if (state is null || !HistoryContinuationMatches(state, handle.NodeId, historyEpoch) || state.Kind != HistoryCursorKind.Events || state.Tagname != sourceName)
|
||||
{
|
||||
errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
|
||||
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadContinuationPointInvalid };
|
||||
return;
|
||||
}
|
||||
|
||||
sourceName = state.Tagname;
|
||||
startUtc = state.NextStartUtc;
|
||||
endUtc = state.EndUtc;
|
||||
boundarySkip = state.BoundarySkipCount;
|
||||
@@ -7956,8 +8025,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
// continuation point (the walk itself cannot flag truncation).
|
||||
var want = numValuesPerNode == 0 ? 0u : (uint)Math.Min(uint.MaxValue - 1L, (long)fetch + 1);
|
||||
var (rows, next) = await ReverseEventsReader.ReadAsync(
|
||||
source, sourceName, startUtc, endUtc, want, MaxTieClusterOverfetch, Clock.GetUtcNow().UtcDateTime,
|
||||
walkHint, ct)
|
||||
(from, to, cap, token) => ReadSourcesAsync(from, to, cap, rev: false, token), source.TimestampResolutionTicks,
|
||||
sourceName, startUtc, endUtc, want, MaxTieClusterOverfetch, Clock.GetUtcNow().UtcDateTime, walkHint, ct)
|
||||
.ConfigureAwait(false);
|
||||
walkHint = next;
|
||||
var more = want > 0 && rows.Count > fetch;
|
||||
@@ -7966,8 +8035,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
}
|
||||
else
|
||||
{
|
||||
sourceResult = await source.ReadEventsAsync(
|
||||
sourceName, startUtc, endUtc, fetch, reverse, ct).ConfigureAwait(false);
|
||||
sourceResult = await ReadSourcesAsync(startUtc, endUtc, fetch, reverse, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Truncation is the SOURCE's word (non-null continuation point) — never inferred from the count, so a
|
||||
@@ -8004,8 +8072,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
// with an explicit bounded cap and page WITHIN it (same scheme as raw).
|
||||
var resolution = Math.Max(1L, source.TimestampResolutionTicks);
|
||||
var overfetchCap = (int)Math.Min(int.MaxValue - 1L, (long)Math.Max(1, MaxTieClusterOverfetch) + 1);
|
||||
IReadOnlyList<HistoricalEvent> cluster = (await source.ReadEventsAsync(
|
||||
sourceName, startUtc, startUtc.AddTicks(resolution), overfetchCap, reverse: false, ct)
|
||||
IReadOnlyList<HistoricalEvent> cluster = (await ReadSourcesAsync(
|
||||
startUtc, startUtc.AddTicks(resolution), overfetchCap, rev: false, ct)
|
||||
.ConfigureAwait(false)).Events;
|
||||
|
||||
// A walked read emitted its ties sorted by EventId; the gateway returns them in any order and its
|
||||
@@ -8041,7 +8109,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
if (nextStartUtc is { } resumeAt)
|
||||
{
|
||||
pendingCursor = new HistoryContinuationState(
|
||||
sourceName ?? string.Empty, resumeAt, endUtc, nextSkip, numValuesPerNode, HistoryCursorKind.Events,
|
||||
sourceName, resumeAt, endUtc, nextSkip, numValuesPerNode, HistoryCursorKind.Events,
|
||||
Reverse: reverse, SegmentWidthTicks: walkHint.WidthTicks, EmptyFromTicks: walkHint.EmptyFromTicks,
|
||||
EmptyToTicks: walkHint.EmptyToTicks);
|
||||
}
|
||||
@@ -8054,7 +8122,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
var skip = 0;
|
||||
for (var i = events.Count - 1; i >= 0 && events[i].EventTimeUtc == boundary; i--) skip++;
|
||||
pendingCursor = new HistoryContinuationState(
|
||||
sourceName ?? string.Empty, boundary, endUtc, skip, numValuesPerNode, HistoryCursorKind.Events,
|
||||
sourceName, boundary, endUtc, skip, numValuesPerNode, HistoryCursorKind.Events,
|
||||
Reverse: reverse, SegmentWidthTicks: walkHint.WidthTicks, EmptyFromTicks: walkHint.EmptyFromTicks,
|
||||
EmptyToTicks: walkHint.EmptyToTicks);
|
||||
}
|
||||
@@ -8062,6 +8130,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2, INodeManager3
|
||||
// The where-clause filters AFTER the page's cursor was taken from the unfiltered events, so paging (time,
|
||||
// boundary skip) is exactly as without a filter: a page may come back with fewer events — even none — and a
|
||||
// continuation point, never skipping or repeating one.
|
||||
// #886: an AVEVA row naming a native condition that fires on this folder carries that condition's SourceNode and
|
||||
// ConditionName, as the live event does. Rewritten after paging: EventId and time are untouched.
|
||||
events = scope.ResolveConditions(events);
|
||||
var historyEvent = ProjectEvents(events, selectClauses, where, filterContext);
|
||||
var outboundCp = pendingCursor is null ? null : SaveHistoryContinuation(session, handle.NodeId, historyEpoch, pendingCursor);
|
||||
results[handle.Index] = new SdkHistoryReadResult
|
||||
|
||||
@@ -27,9 +27,33 @@ internal static class ReverseEventsReader
|
||||
/// <param name="ct">Cancellation.</param>
|
||||
/// <returns>The events, newest first, and the hint for the next page.</returns>
|
||||
/// <exception cref="HistoryReadLimitExceededException">One timestamp holds more than the tie budget.</exception>
|
||||
public static async Task<ReverseEventsPage> ReadAsync(
|
||||
public static Task<ReverseEventsPage> ReadAsync(
|
||||
IHistorianDataSource source, string? sourceName, DateTime hi, DateTime lo, uint want, int maxTieCluster,
|
||||
DateTime nowUtc, ReverseWalkHint hint, CancellationToken ct)
|
||||
DateTime nowUtc, ReverseWalkHint hint, CancellationToken ct) =>
|
||||
ReadAsync(
|
||||
(start, end, cap, token) => source.ReadEventsAsync(sourceName, start, end, cap, reverse: false, token),
|
||||
source.TimestampResolutionTicks, sourceName, hi, lo, want, maxTieCluster, nowUtc, hint, ct);
|
||||
|
||||
/// <summary>
|
||||
/// Reads <c>(lo, hi]</c> newest-first from a forward event reader — the form a folder with several event sources
|
||||
/// uses (<see cref="EventSourceFanOut"/>, Gitea #886), whose merged reads stand in for one source's.
|
||||
/// </summary>
|
||||
/// <param name="readForward">Reads <c>[start, end]</c> forward with a cap (<c>int.MaxValue</c> = none).</param>
|
||||
/// <param name="resolutionTicks">The backend's timestamp resolution.</param>
|
||||
/// <param name="sourceName">The source (or source set) named in a limit message.</param>
|
||||
/// <param name="hi">The later (inclusive) bound.</param>
|
||||
/// <param name="lo">The earlier (exclusive) bound.</param>
|
||||
/// <param name="want">How many events; <c>0</c> = all in the window (one forward read).</param>
|
||||
/// <param name="maxTieCluster">The tie budget (<c>MaxTieClusterOverfetch</c>) — a ceiling only.</param>
|
||||
/// <param name="nowUtc">Now, for the look-ahead clamp.</param>
|
||||
/// <param name="hint">What the previous page carried (default = none).</param>
|
||||
/// <param name="ct">Cancellation.</param>
|
||||
/// <returns>The events, newest first, and the hint for the next page.</returns>
|
||||
/// <exception cref="HistoryReadLimitExceededException">One timestamp holds more than the tie budget.</exception>
|
||||
public static async Task<ReverseEventsPage> ReadAsync(
|
||||
Func<DateTime, DateTime, int, CancellationToken, Task<HistoricalEventsResult>> readForward, long resolutionTicks,
|
||||
string? sourceName, DateTime hi, DateTime lo, uint want, int maxTieCluster, DateTime nowUtc, ReverseWalkHint hint,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var budget = Math.Max(1, maxTieCluster);
|
||||
var (rows, next) = await ReverseWalk.WalkAsync<HistoricalEvent>(
|
||||
@@ -37,11 +61,10 @@ internal static class ReverseEventsReader
|
||||
{
|
||||
// cap 0 = the whole window: int.MaxValue is the events contract's "no cap" (a non-positive value would
|
||||
// mean the backend's DEFAULT cap).
|
||||
var r = await source.ReadEventsAsync(sourceName, start, end, cap == 0 ? int.MaxValue : cap, reverse: false, token)
|
||||
.ConfigureAwait(false);
|
||||
var r = await readForward(start, end, cap == 0 ? int.MaxValue : cap, token).ConfigureAwait(false);
|
||||
return new ForwardSegmentRead<HistoricalEvent>(r.Events, r.ContinuationPoint is not null);
|
||||
},
|
||||
ev => ev.EventTimeUtc.Ticks, EventIdTieOrder.Instance, hi, lo, want, budget, source.TimestampResolutionTicks,
|
||||
ev => ev.EventTimeUtc.Ticks, EventIdTieOrder.Instance, hi, lo, want, budget, resolutionTicks,
|
||||
nowUtc, hint,
|
||||
at => new HistoryReadLimitExceededException(budget,
|
||||
$"A reverse events read of '{sourceName}' at {at:O} found more than {budget} events within one millisecond; the " +
|
||||
|
||||
@@ -54,6 +54,10 @@ public sealed class SdkAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgicalAddre
|
||||
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm)
|
||||
=> _nodeManager.WireAlarmNotifiers(alarmNodeId, alarmRealm, notifierFolderNodeIds, notifierFolderRealm);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void BindNativeAlarmHistory(string alarmNodeId, AddressSpaceRealm alarmRealm, string alarmReference)
|
||||
=> _nodeManager.BindNativeAlarmHistory(alarmNodeId, alarmRealm, alarmReference);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm)
|
||||
=> _nodeManager.EnsureFolder(folderNodeId, parentNodeId, displayName, realm);
|
||||
|
||||
Reference in New Issue
Block a user