using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.Sql.Common; /// What the backend did with one HistoryUpdate winner row. public enum UpsertOutcome { /// The row was absent and was inserted. Inserted, /// The row existed and was replaced. Replaced, } /// The database-independent half of one UpdateDataAsync call (see ). public sealed class UpdatePlan { /// Creates a plan from the per-sample results and the winning rows. /// The per-sample status results, indexed by request position. /// The winning sample rows with their request indices. /// The per-sample tick keys, or null where a sample has no key. /// Maps each tick to the index of the sample that won it. internal UpdatePlan(uint?[] results, IReadOnlyList<(int Index, HistorianSampleRow Row)> winners, long?[] keys, IReadOnlyDictionary winnerByTick) { Results = results; Winners = winners; Keys = keys; WinnerByTick = winnerByTick; } /// Pre-decided codes (invalid ts, NaN, superseded duplicate…); null = decided by the backend. public uint?[] Results { get; } /// Rows to send, de-duplicated per mode, in input order. public IReadOnlyList<(int Index, HistorianSampleRow Row)> Winners { get; } /// Per input item: its (truncated) timestamp ticks, or null when the timestamp is invalid. internal long?[] Keys { get; } /// (Truncated) tick → input index of the item actually sent. internal IReadOnlyDictionary WinnerByTick { get; } } /// /// Per-item result rules for OPC UA HistoryUpdate (spec §4 "Updates"): exactly one status per input item, in input /// order. /// Duplicate timestamps within one request (compared at the backend's resolution): Insert — the first /// occurrence is applied, later ones are BadEntryExists; Replace/Update — last wins, and every earlier /// occurrence of that timestamp reports the same code as the winning one. DeleteAtTime — the first occurrence /// reports the real outcome, later ones BadNoEntryExists. /// Invalid items. A null or timestamp is BadInvalidTimestamp. /// A Double NaN/±Infinity is rejected with BadInvalidArgument. An Empty (null) value is only accepted with a /// Bad status (an operator-authored outage marker); with a Good or Uncertain status it is BadInvalidArgument. /// Other items still proceed. /// Tag names over characters are refused, never truncated: /// every item reports BadInvalidArgument and nothing is sent. /// public static class HistoryUpdatePlanner { /// The pre-pass: classifies every item and picks the winner row per timestamp. /// Historian tag name. /// Insert, Replace or Update. /// Input items, in request order. /// 1 = 100 ns (SQL Server); 10 = timestamps truncated to µs BEFORE de-duplication (QuestDB). /// The plan. public static UpdatePlan Plan(string tag, HistoryUpdateMode mode, IReadOnlyList values, long resolutionTicks = 1) { ArgumentNullException.ThrowIfNull(tag); ArgumentNullException.ThrowIfNull(values); ArgumentOutOfRangeException.ThrowIfLessThan(resolutionTicks, 1); var results = new uint?[values.Count]; var winner = new Dictionary(); // tick -> index of the item actually sent if (!HistorianTagNames.IsValid(tag)) { Array.Fill(results, HistorianStatusCodes.BadInvalidArgument); return new UpdatePlan(results, [], new long?[values.Count], winner); } var times = new DateTime[values.Count]; var keys = new long?[values.Count]; for (var i = 0; i < values.Count; i++) { var v = values[i]; if (v.TimestampUtc is not { } ts || ts == DateTime.MinValue) { results[i] = HistorianStatusCodes.BadInvalidTimestamp; continue; } times[i] = LiveWritePreparer.Truncate(ts, resolutionTicks); keys[i] = times[i].Ticks; if ((v.Value.Kind == HistorianValueKind.Double && !double.IsFinite(v.Value.Number)) || (v.Value.Kind == HistorianValueKind.Empty && !StatusBits.IsBad(v.StatusCode))) { results[i] = HistorianStatusCodes.BadInvalidArgument; continue; } var key = times[i].Ticks; if (!winner.TryGetValue(key, out _)) winner[key] = i; else if (mode == HistoryUpdateMode.Insert) results[i] = HistorianStatusCodes.BadEntryExists; // first occurrence stays the winner else winner[key] = i; // last wins } var send = winner.Values.OrderBy(i => i) .Select(i => (i, new HistorianSampleRow(times[i], values[i].Value, values[i].StatusCode))) .ToList(); return new UpdatePlan(results, send, keys, winner); } /// The post-pass: fills in each winner's code from what the backend wrote, then the superseded duplicates. /// The plan from . /// The same mode passed to . /// Ticks of each winner that the backend actually wrote → Inserted/Replaced; absent ⇒ not /// written (Insert: the row already existed ⇒ BadEntryExists; Replace: no row ⇒ BadNoEntryExists). /// One status per input item, in input order. public static IReadOnlyList Complete(UpdatePlan plan, HistoryUpdateMode mode, IReadOnlyDictionary outcomeByTick) { ArgumentNullException.ThrowIfNull(plan); ArgumentNullException.ThrowIfNull(outcomeByTick); var results = (uint?[])plan.Results.Clone(); // No written row means the absent branch: Insert => matched (exists); Replace => not matched. var absent = mode == HistoryUpdateMode.Replace ? HistorianStatusCodes.BadNoEntryExists : HistorianStatusCodes.BadEntryExists; foreach (var (index, row) in plan.Winners) results[index] = outcomeByTick.TryGetValue(row.TimeUtc.Ticks, out var o) ? o == UpsertOutcome.Inserted ? HistorianStatusCodes.GoodEntryInserted : HistorianStatusCodes.GoodEntryReplaced : absent; var final = new uint[results.Length]; for (var i = 0; i < results.Length; i++) final[i] = results[i] ?? 0u; // Superseded earlier duplicates (Replace/Update) share the winner's code. if (mode != HistoryUpdateMode.Insert) for (var i = 0; i < results.Length; i++) if (plan.Keys[i] is { } key && results[i] is null && plan.WinnerByTick.TryGetValue(key, out var w) && w != i) final[i] = final[w]; return final; } /// /// DeleteAtTime results: ⇒ BadInvalidTimestamp; the first occurrence of a /// deleted time ⇒ Good; everything else (unknown tag, no row, later duplicate) ⇒ BadNoEntryExists. /// /// Requested times, in request order (already at the backend's resolution). /// Ticks of the rows the backend actually deleted. /// Whether the tag exists. /// One status per requested time. public static IReadOnlyList DeleteAtTimeResults(IReadOnlyList times, ISet deletedTicks, bool tagKnown) { ArgumentNullException.ThrowIfNull(times); ArgumentNullException.ThrowIfNull(deletedTicks); var results = new uint[times.Count]; var first = new Dictionary(); for (var i = 0; i < times.Count; i++) { results[i] = HistorianStatusCodes.BadNoEntryExists; if (times[i] == DateTime.MinValue) results[i] = HistorianStatusCodes.BadInvalidTimestamp; else first.TryAdd(times[i].Ticks, i); } if (!tagKnown) return results; foreach (var (ticks, idx) in first) if (deletedTicks.Contains(ticks)) results[idx] = HistorianStatusCodes.Good; return results; } /// DeleteRaw result: unknown tag or nothing deleted ⇒ BadNoData; otherwise Good. /// Whether the tag exists. /// Rows the backend deleted. /// The status. public static uint DeleteRawResult(bool tagKnown, long rowsAffected) => tagKnown && rowsAffected > 0 ? HistorianStatusCodes.Good : HistorianStatusCodes.BadNoData; }