using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; /// A native condition an AVEVA history row can resolve to (Gitea #886). /// The condition's id (its RawPath), from which the server resolves the row's SourceNode. /// The live condition's ConditionName. internal sealed record EventHistoryCondition(string AlarmId, string ConditionName); /// /// 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. /// internal sealed class EventHistoryScope { private static readonly IReadOnlyDictionary NoConditions = new Dictionary(); private readonly IReadOnlyDictionary _conditions; private EventHistoryScope(IReadOnlyList sources, IReadOnlyDictionary 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); } /// The sources to read: distinct, ordinal-sorted (the folder's own first when it is the only one). public IReadOnlyList Sources { get; } /// The identity a continuation point is bound to: the whole source set. public string CursorKey { get; } /// A scope of one source and no Galaxy conditions (every non-Galaxy folder). /// The folder's own source. /// The scope. public static EventHistoryScope Single(string source) => new([source], NoConditions); /// A folder's own source plus the Galaxy objects behind it. /// The folder's own source. /// The Galaxy objects of the native conditions that fire on it (duplicates allowed). /// Those conditions by Galaxy alarm reference (case-insensitive). /// The scope. public static EventHistoryScope Create( string ownSource, IEnumerable? objects, IReadOnlyDictionary conditions) { var sources = new SortedSet(StringComparer.Ordinal) { ownSource }; foreach (var o in objects ?? []) sources.Add(o); return new EventHistoryScope(sources.ToList(), conditions); } /// /// Give each row whose names one of this folder's native conditions /// that condition's id (so its SourceNode resolves) and live ConditionName. Other rows are unchanged. /// /// A page of events. /// The page, resolved. public IReadOnlyList ResolveConditions(IReadOnlyList events) { if (_conditions.Count == 0 || events.Count == 0) return events; List? 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; } } /// /// Reads several event sources as one (Gitea #886): one backend read per source (the historiangw ReadEvents /// filter is a single predicate, so there is no multi-source request), merged, de-duplicated by EventId and cut to the /// cap. /// /// /// /// Merge order is (EventTimeUtc, source, arrival): 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. /// /// /// Truncation stays honest. 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. /// /// A single source is passed straight through, so a folder with one source reads exactly as before #886. /// internal static class EventSourceFanOut { /// Reads over one window and merges them. /// The backend. /// The event sources (at least one). /// The window start (the later bound for a reverse read). /// The window end. /// The cap, passed to every source; <= 0 is the backend's default cap. /// Newest first. /// Cancellation. /// The merged events, and a non-null continuation point when more exist. public static async Task ReadAsync( IHistorianDataSource source, IReadOnlyList 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(); var seen = new HashSet(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(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 all, int next, DateTime h) { var previous = all[next - 1]; return previous.Source != all[next].Source && truncatedAt[previous.Source] == h; } } /// One merged event: the event, its source's position in the list, and its position in that source's read. private readonly record struct Merged(HistoricalEvent Event, int Source, int Arrival); /// Time in the read's direction, then source position (reversed for a reverse read), then arrival. private sealed class MergeOrder(bool reverse) : IComparer { 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); } } }