fix(history): a folder's event history reads the Galaxy objects behind its native conditions (#886)
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:
Joseph Doherty
2026-11-12 11:34:50 -05:00
parent 1e1fad76c4
commit 3a312ffdd1
25 changed files with 1531 additions and 95 deletions
@@ -59,6 +59,12 @@ public sealed class DeferredAddressSpaceSink : IOpcUaAddressSpaceSink, ISurgical
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm)
=> _inner.WireAlarmNotifiers(alarmNodeId, alarmRealm, notifierFolderNodeIds, notifierFolderRealm);
/// <inheritdoc />
// Forwarded for the same reason as WireAlarmNotifiers: the interface default is a no-op, so a missing forward would
// leave every driver-role host's folders without their Galaxy event-history sources (#886).
public void BindNativeAlarmHistory(string alarmNodeId, AddressSpaceRealm alarmRealm, string alarmReference)
=> _inner.BindNativeAlarmHistory(alarmNodeId, alarmRealm, alarmReference);
/// <inheritdoc />
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm)
=> _inner.EnsureFolder(folderNodeId, parentNodeId, displayName, realm);
@@ -134,6 +134,21 @@ public interface IOpcUaAddressSpaceSink
void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm,
IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm);
/// <summary>
/// Gitea #886 — record the upstream (AVEVA) reference of an already-materialised NATIVE alarm condition: the
/// Galaxy alarm reference (<c>tag_name.AlarmAttribute</c>) the backing raw tag dials. AVEVA stores that alarm's
/// history, and its object's own events, under the reference's object (<c>tag_name</c>), so every folder the
/// condition fires on live (its parent and each folder <see cref="WireAlarmNotifiers"/> wired) also reads that
/// object's event history, and an AVEVA history row naming this reference resolves its <c>SourceNode</c> and
/// <c>ConditionName</c> to this condition. Call it after <see cref="MaterialiseAlarmCondition"/>; idempotent; a
/// condition that is not materialised is a no-op. A rebuild or the condition's removal forgets the reference.
/// The default does nothing (a sink with no event history).
/// </summary>
/// <param name="alarmNodeId">The native alarm condition's node id (== the backing tag's RawPath).</param>
/// <param name="alarmRealm">The namespace realm the condition lives in (Raw for native alarms).</param>
/// <param name="alarmReference">The Galaxy alarm reference, e.g. <c>Oven_007.TempHiAlarm</c>.</param>
void BindNativeAlarmHistory(string alarmNodeId, AddressSpaceRealm alarmRealm, string alarmReference) { }
/// <summary>
/// Ensure a folder node exists under the given parent. Used by <c>AddressSpaceApplier</c> to
/// materialise the UNS Area/Line/Equipment hierarchy in the address space. When
@@ -288,6 +303,9 @@ public sealed class NullOpcUaAddressSpaceSink : IOpcUaAddressSpaceSink
/// <inheritdoc />
public void WireAlarmNotifiers(string alarmNodeId, AddressSpaceRealm alarmRealm, IReadOnlyList<string> notifierFolderNodeIds, AddressSpaceRealm notifierFolderRealm) { }
/// <inheritdoc />
public void BindNativeAlarmHistory(string alarmNodeId, AddressSpaceRealm alarmRealm, string alarmReference) { }
/// <inheritdoc />
public void EnsureFolder(string folderNodeId, string? parentNodeId, string displayName, AddressSpaceRealm realm) { }
@@ -0,0 +1,37 @@
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// <summary>
/// The Galaxy alarm priority → OPC UA Part 9 severity mapping, shared by live alarms (the Galaxy driver's
/// <c>MxAccessSeverityMapper</c>) and AVEVA alarm history (<c>priority</c>, Gitea #886) so the two agree.
/// </summary>
/// <remarks>
/// The four-bucket ladder (250 / 500 / 750 / 1000 — Low / Medium / High / Critical) is the one v1's
/// <c>GalaxyAlarmTracker</c> exposed; out-of-range inputs clamp into the nearest bucket. ⚠️ It treats a higher number
/// as more severe, while AVEVA ranks priority 1 as the most urgent: lmxopcua#887 tracks that. Change it here only, so
/// live and history move together.
/// </remarks>
public static class GalaxyAlarmPriority
{
/// <summary>OPC UA severity of the Low bucket (raw &lt; 250).</summary>
public const int OpcUaSeverityLow = 250;
/// <summary>OPC UA severity of the Medium bucket (raw 250–499).</summary>
public const int OpcUaSeverityMedium = 500;
/// <summary>OPC UA severity of the High bucket (raw 500–749).</summary>
public const int OpcUaSeverityHigh = 750;
/// <summary>OPC UA severity of the Critical bucket (raw 750 and above).</summary>
public const int OpcUaSeverityCritical = 1000;
/// <summary>Maps a raw Galaxy priority onto the bucket and its OPC UA severity.</summary>
/// <param name="rawPriority">The raw value (0–999; clamped).</param>
/// <returns>The bucket and its OPC UA Part 9 numeric severity.</returns>
public static (AlarmSeverity Bucket, int OpcUaSeverity) Map(int rawPriority) => rawPriority switch
{
< 250 => (AlarmSeverity.Low, OpcUaSeverityLow),
< 500 => (AlarmSeverity.Medium, OpcUaSeverityMedium),
< 750 => (AlarmSeverity.High, OpcUaSeverityHigh),
_ => (AlarmSeverity.Critical, OpcUaSeverityCritical),
};
}
@@ -0,0 +1,75 @@
using System.Text.Json;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// <summary>
/// The Galaxy (<see cref="DriverTypeNames.Galaxy"/>) tag reference: the <c>attributeRef</c> a Galaxy raw tag's
/// <c>TagConfig</c> carries, <c>tag_name.AttributeName</c>, which the driver dials through MXAccess. One parser for the
/// driver (which dials it) and the address-space composer (which names the AVEVA event source it implies, Gitea #886),
/// so the two can never disagree about which tags carry one.
/// </summary>
public static class GalaxyAttributeRef
{
/// <summary>The <c>TagConfig</c> key (camelCase; matched case-insensitively).</summary>
public const string Key = "attributeRef";
/// <summary>
/// Read the Galaxy dialled address from a tag's <c>TagConfig</c> JSON — the camelCase <c>attributeRef</c> key (the v3
/// rename of the pre-v3 PascalCase <c>FullName</c>). Case-insensitive on the property name for authoring tolerance;
/// returns null on an absent/blank/non-string value or an unparseable blob.
/// </summary>
/// <param name="tagConfigJson">The tag's <c>TagConfig</c> JSON.</param>
/// <returns>The attributeRef, or null.</returns>
public static string? TryRead(string? tagConfigJson)
{
if (string.IsNullOrWhiteSpace(tagConfigJson)) return null;
try
{
using var doc = JsonDocument.Parse(tagConfigJson);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
foreach (var prop in doc.RootElement.EnumerateObject())
{
if (!prop.NameEquals(Key) && !string.Equals(prop.Name, Key, StringComparison.OrdinalIgnoreCase)) continue;
if (prop.Value.ValueKind != JsonValueKind.String) return null;
var v = prop.Value.GetString();
return string.IsNullOrWhiteSpace(v) ? null : v;
}
}
catch (JsonException)
{
// Malformed blob: no dialable address.
}
return null;
}
/// <summary>
/// The AVEVA alarm reference of a native-alarm tag, or null: the tag's <see cref="TryRead">attributeRef</see> when its
/// driver is the Galaxy driver, otherwise null (no other driver's alarms are stored by AVEVA under a Galaxy name).
/// </summary>
/// <param name="driverType">The owning driver's <c>DriverType</c>.</param>
/// <param name="tagConfigJson">The tag's <c>TagConfig</c> JSON.</param>
/// <returns>The Galaxy alarm reference (<c>tag_name.AlarmAttribute</c>), or null.</returns>
public static string? AlarmReferenceOf(string? driverType, string? tagConfigJson) =>
string.Equals(driverType, DriverTypeNames.Galaxy, StringComparison.Ordinal) ? TryRead(tagConfigJson) : null;
/// <summary>
/// The Galaxy object (<c>tag_name</c>) a reference belongs to: the text before the first <c>.</c>, or the whole
/// reference when it has none. This is AVEVA's <c>Source_Object</c> for the object's events and its attributes'
/// alarms. Null for a blank reference or one that starts with a <c>.</c>.
/// </summary>
/// <param name="reference">A Galaxy reference, e.g. <c>Oven_007.TempHiAlarm</c>.</param>
/// <returns>The object name, e.g. <c>Oven_007</c>.</returns>
public static string? ObjectNameOf(string? reference)
{
if (string.IsNullOrWhiteSpace(reference)) return null;
var trimmed = reference.Trim();
var dot = trimmed.IndexOf('.');
return dot switch
{
< 0 => trimmed,
0 => null,
_ => trimmed[..dot],
};
}
}
@@ -128,6 +128,11 @@ public sealed class HistoryReadLimitExceededException : InvalidOperationExceptio
/// The stored alarm id (a native alarm's RawPath / a scripted alarm's id) — what the server resolves the event's
/// <c>SourceNode</c> (the condition node) from, when that condition is materialised.
/// </param>
/// <param name="ConditionReference">
/// The upstream system's own reference to the alarm condition, when the backend has one — AVEVA's
/// <c>source_conditionvariable</c> (<c>tag_name.AlarmAttribute</c>) on a Galaxy alarm row. The server resolves it to the
/// native condition that dials the same reference, among those that fire on the folder being read (Gitea #886).
/// </param>
public sealed record HistoricalEvent(
string EventId,
string? SourceName,
@@ -137,7 +142,8 @@ public sealed record HistoricalEvent(
ushort Severity,
string? EventTypeName = null,
string? ConditionName = null,
string? AlarmId = null);
string? AlarmId = null,
string? ConditionReference = null);
/// <summary>Result of a <see cref="IHistorianDataSource.ReadEventsAsync(string?, DateTime, DateTime, int, CancellationToken)"/> call.</summary>
/// <param name="Events">Events ordered by <c>EventTimeUtc</c> in the read's direction — ascending, or descending for a reverse read.</param>
@@ -454,31 +454,7 @@ public sealed class GalaxyDriver
/// on the property name for authoring tolerance; returns null on an absent/blank/non-string value
/// or unparseable blob (the entry is then skipped, never dialled).
/// </summary>
private static string? TryReadAttributeRef(string tagConfigJson)
{
if (string.IsNullOrWhiteSpace(tagConfigJson)) return null;
try
{
using var doc = JsonDocument.Parse(tagConfigJson);
if (doc.RootElement.ValueKind != JsonValueKind.Object) return null;
foreach (var prop in doc.RootElement.EnumerateObject())
{
if (!prop.NameEquals("attributeRef")
&& !string.Equals(prop.Name, "attributeRef", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (prop.Value.ValueKind != JsonValueKind.String) return null;
var v = prop.Value.GetString();
return string.IsNullOrWhiteSpace(v) ? null : v;
}
}
catch (JsonException)
{
// Malformed blob — treat as un-dialable; BuildRawTagTables logs the skip.
}
return null;
}
private static string? TryReadAttributeRef(string tagConfigJson) => GalaxyAttributeRef.TryRead(tagConfigJson);
/// <summary>RawPath → Galaxy attributeRef for MXAccess dialling; identity on a miss.</summary>
private string ToAttributeRef(string rawPath) =>
@@ -24,13 +24,13 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
internal static class MxAccessSeverityMapper
{
/// <summary>OPC UA Part 9 numeric severity for the Low bucket (0-249 MxAccess).</summary>
public const int OpcUaSeverityLow = 250;
public const int OpcUaSeverityLow = GalaxyAlarmPriority.OpcUaSeverityLow;
/// <summary>OPC UA Part 9 numeric severity for the Medium bucket (250-499 MxAccess).</summary>
public const int OpcUaSeverityMedium = 500;
public const int OpcUaSeverityMedium = GalaxyAlarmPriority.OpcUaSeverityMedium;
/// <summary>OPC UA Part 9 numeric severity for the High bucket (500-749 MxAccess).</summary>
public const int OpcUaSeverityHigh = 750;
public const int OpcUaSeverityHigh = GalaxyAlarmPriority.OpcUaSeverityHigh;
/// <summary>OPC UA Part 9 numeric severity for the Critical bucket (750+ MxAccess).</summary>
public const int OpcUaSeverityCritical = 1000;
public const int OpcUaSeverityCritical = GalaxyAlarmPriority.OpcUaSeverityCritical;
/// <summary>
/// Translate a raw MXAccess severity into the four-bucket
@@ -38,20 +38,6 @@ internal static class MxAccessSeverityMapper
/// </summary>
/// <param name="rawMxAccessSeverity">The raw MXAccess severity value (0-999 range, clamped if out of range).</param>
/// <returns>The mapped four-bucket <see cref="AlarmSeverity"/> and its OPC UA Part 9 numeric severity.</returns>
public static (AlarmSeverity Bucket, int OpcUaSeverity) Map(int rawMxAccessSeverity)
{
if (rawMxAccessSeverity < 250)
{
return (AlarmSeverity.Low, OpcUaSeverityLow);
}
if (rawMxAccessSeverity < 500)
{
return (AlarmSeverity.Medium, OpcUaSeverityMedium);
}
if (rawMxAccessSeverity < 750)
{
return (AlarmSeverity.High, OpcUaSeverityHigh);
}
return (AlarmSeverity.Critical, OpcUaSeverityCritical);
}
// One table for live and history (Gitea #886): GalaxyAlarmPriority, which AVEVA history rows map their priority through.
public static (AlarmSeverity Bucket, int OpcUaSeverity) Map(int rawMxAccessSeverity) => GalaxyAlarmPriority.Map(rawMxAccessSeverity);
}
@@ -8,6 +8,20 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Gateway.Mapping;
/// Maps a gateway wire event (<see cref="HistorianEvent"/>) onto the driver-agnostic
/// <see cref="HistoricalEvent"/> consumed by the Server's HistoryReadEvents path.
/// </summary>
/// <remarks>
/// <para>
/// Property names are matched case-insensitively (Gitea #886). AVEVA stores every event property under a lower-case
/// key: its own A&amp;E rows carry <c>priority</c>, <c>alarm_id</c>, <c>source_conditionvariable</c>, and OtOpcUa's own
/// events, written as <c>AlarmName</c> / <c>AlarmId</c> / <c>Severity</c> / <c>Message</c>, come back as
/// <c>alarmname</c> / <c>alarmid</c> / <c>severity</c> / <c>message</c>.
/// </para>
/// <para>
/// Severity: an AVEVA row's <c>priority</c> maps through <see cref="GalaxyAlarmPriority"/>, the table live Galaxy alarms
/// use, so a row and its live event agree. AVEVA's own <c>severity</c> on such a row (1–4, 0 for a system event) is not on
/// the OPC UA scale and is ignored. A row with no <c>priority</c> (OtOpcUa's own) takes <c>severity</c>, clamped to
/// 1–1000.
/// </para>
/// </remarks>
internal static class EventMapper
{
/// <summary>OPC UA severity range (Part 9): 1 (lowest) … 1000 (highest).</summary>
@@ -19,13 +33,16 @@ internal static class EventMapper
/// <returns>The driver-agnostic historical event.</returns>
public static HistoricalEvent ToHistoricalEvent(HistorianEvent historianEvent)
{
var properties = historianEvent.Properties;
// Message: prefer the "Message" property, else fall back to the event Type (best-effort
// render); never null-crash on a missing property.
string? message;
if (historianEvent.Properties.TryGetValue("Message", out var m) && !string.IsNullOrEmpty(m))
message = m;
else
message = string.IsNullOrEmpty(historianEvent.Type) ? null : historianEvent.Type;
var message = Property(properties, "Message")
?? (string.IsNullOrEmpty(historianEvent.Type) ? null : historianEvent.Type);
// AVEVA's reference to the alarm condition (tag_name.AlarmAttribute); the server resolves it to the native
// condition that dials it, when one fires on the folder being read.
var conditionReference = Property(properties, "source_conditionvariable");
return new HistoricalEvent(
EventId: historianEvent.Id,
@@ -33,15 +50,32 @@ internal static class EventMapper
EventTimeUtc: historianEvent.EventTime?.ToDateTime() ?? default, // Utc kind
ReceivedTimeUtc: historianEvent.ReceivedTime?.ToDateTime() ?? default, // Utc kind
Message: message,
Severity: ParseSeverity(historianEvent.Properties),
Severity: ParseSeverity(properties),
// What GatewayAlarmHistorianWriter sent (AlarmEventMapper): Type = AlarmTypeName, AlarmName / AlarmId properties.
EventTypeName: string.IsNullOrEmpty(historianEvent.Type) ? null : historianEvent.Type,
ConditionName: Property(historianEvent.Properties, "AlarmName"),
AlarmId: Property(historianEvent.Properties, "AlarmId"));
ConditionName: Property(properties, "AlarmName") ?? AttributeOf(conditionReference),
AlarmId: Property(properties, "AlarmId") ?? Property(properties, "alarm_id"),
ConditionReference: conditionReference);
}
private static string? Property(IDictionary<string, string> properties, string name) =>
properties.TryGetValue(name, out var v) && !string.IsNullOrEmpty(v) ? v : null;
/// <summary>A property by name, exact first, else case-insensitively; null when absent or empty.</summary>
private static string? Property(IDictionary<string, string> properties, string name)
{
if (properties.TryGetValue(name, out var exact)) return string.IsNullOrEmpty(exact) ? null : exact;
foreach (var (key, value) in properties)
if (string.Equals(key, name, StringComparison.OrdinalIgnoreCase))
return string.IsNullOrEmpty(value) ? null : value;
return null;
}
/// <summary>The attribute part of a Galaxy reference (<c>Oven_007.TempHiAlarm</c> ⇒ <c>TempHiAlarm</c>), or the whole
/// reference when it has no object prefix.</summary>
private static string? AttributeOf(string? reference)
{
if (reference is null) return null;
var dot = reference.IndexOf('.');
return dot > 0 && dot < reference.Length - 1 ? reference[(dot + 1)..] : reference;
}
/// <summary>Maps a batch of gateway events to historical events, in order.</summary>
/// <param name="events">The gateway wire events.</param>
@@ -55,20 +89,20 @@ internal static class EventMapper
}
/// <summary>
/// Parses an OPC UA severity from the "Severity" property (else "Priority"), clamped to
/// <c>[1, 1000]</c>. Missing or unparseable values default to the minimum severity (1).
/// The OPC UA severity: an AVEVA row's <c>priority</c> through the live Galaxy table, else the <c>Severity</c> property
/// clamped to <c>[1, 1000]</c>. Missing or unparseable values default to the minimum severity (1).
/// </summary>
private static ushort ParseSeverity(IDictionary<string, string> properties)
{
string? raw = null;
if (properties.TryGetValue("Severity", out var severity))
raw = severity;
else if (properties.TryGetValue("Priority", out var priority))
raw = priority;
if (TryParseInt(Property(properties, "Priority"), out var priority))
return (ushort)GalaxyAlarmPriority.Map(priority).OpcUaSeverity;
if (int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value))
if (TryParseInt(Property(properties, "Severity"), out var value))
return (ushort)Math.Clamp(value, MinSeverity, MaxSeverity);
return MinSeverity;
}
private static bool TryParseInt(string? raw, out int value) =>
int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
}
@@ -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>&lt;= 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);