169 lines
8.9 KiB
C#
169 lines
8.9 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Diagnostics.Metrics;
|
|
using System.Runtime.CompilerServices;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
/// <summary>Consumer-side remote-history evidence for one deployed connection (H4 diagnostics).</summary>
|
|
public sealed record ConsumerHistoryCounts(long Good, long Uncertain, long Bad, int OpenContinuations);
|
|
|
|
/// <summary>
|
|
/// H4 remote-history diagnostics and metrics for one process (plan §6 "Metrics"). It has no dependencies, so the origin
|
|
/// services (<see cref="LocalDataServices"/>), the consumer gateway (<see cref="ProjectedHistoryAccess"/>) and the
|
|
/// diagnostics readers (<see cref="DataConnectionDeploymentRuntime"/>, the driver host) share one instance without a cycle.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>Metrics, on <see cref="OtOpcUaTelemetry.Meter"/>, never carry an id in a label:</para>
|
|
/// <list type="bullet">
|
|
/// <item><see cref="ReadsCounterName"/> — tagged <c>variant</c> (raw | processed | attime | modified),
|
|
/// <c>status_class</c> (good | uncertain | bad) and <c>side</c>: origin = one per item per WIRE CALL served to a peer (a
|
|
/// chunked page's follow-up calls count again); consumer = one per projected node per local OPC UA HistoryRead, with the
|
|
/// status the client got. A node can be both, so <c>side</c> keeps the two from being summed.</item>
|
|
/// <item><see cref="ContinuationsGaugeName"/> — open remote continuations, tagged <c>side</c>: origin cursors held for
|
|
/// peers, and consumer cursors held in local OPC UA sessions (created, neither resumed nor released).</item>
|
|
/// </list>
|
|
/// <para>
|
|
/// The plan's <c>…operations.unknown_bits_dropped</c> is the X0 counter <see cref="UnknownOperationDrops.CounterName"/>
|
|
/// (<c>otopcua.dataconnection.unknown_operations_dropped</c>, tag <c>kind</c>); it is reused, not duplicated.
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed class DataConnectionHistoryDiagnostics
|
|
{
|
|
public const string ReadsCounterName = "otopcua.dataconn.history.reads";
|
|
public const string ContinuationsGaugeName = "otopcua.dataconn.history.continuations.active";
|
|
public const string OriginSide = "origin";
|
|
public const string ConsumerSide = "consumer";
|
|
|
|
private static readonly Counter<long> Reads = OtOpcUaTelemetry.Meter.CreateCounter<long>(ReadsCounterName, unit: "{item}",
|
|
description: "Remote history items answered over data connections (tags: variant = raw|processed|attime; " +
|
|
"status_class = good|uncertain|bad; side = origin|consumer).");
|
|
|
|
// Weak: a process normally holds one instance, tests many; none needs disposing to leave the gauge.
|
|
private static readonly ConditionalWeakTable<DataConnectionHistoryDiagnostics, object> Live = new();
|
|
|
|
static DataConnectionHistoryDiagnostics()
|
|
{
|
|
OtOpcUaTelemetry.Meter.CreateObservableGauge(ContinuationsGaugeName, static () => Observe(), unit: "{continuation}",
|
|
description: "Open remote-history continuations (tag side = origin: cursors held for peers; consumer: cursors held " +
|
|
"in local OPC UA sessions).");
|
|
}
|
|
|
|
private static IEnumerable<Measurement<int>> Observe()
|
|
{
|
|
int origin = 0, consumer = 0;
|
|
foreach (var (instance, _) in Live)
|
|
{
|
|
origin += instance.CaptureOrigin()?.OpenContinuations ?? 0;
|
|
consumer += instance.OpenConsumerContinuations;
|
|
}
|
|
|
|
return
|
|
[
|
|
new Measurement<int>(origin, new KeyValuePair<string, object?>("side", OriginSide)),
|
|
new Measurement<int>(consumer, new KeyValuePair<string, object?>("side", ConsumerSide)),
|
|
];
|
|
}
|
|
|
|
private sealed class Counts
|
|
{
|
|
public long Good, Uncertain, Bad;
|
|
public int Open;
|
|
}
|
|
|
|
private readonly ConcurrentDictionary<string, Counts> _consumer = new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Counts _origin = new();
|
|
private Func<(bool Available, int Sessions, int Open)>? _originState;
|
|
private Func<bool>? _provisionalAvailability;
|
|
|
|
public DataConnectionHistoryDiagnostics() => Live.AddOrUpdate(this, new object());
|
|
|
|
/// <summary>The <c>variant</c> label of a request's details.</summary>
|
|
internal static string Variant(DataHistoryDetails details) => details switch
|
|
{
|
|
DataHistoryRawDetails => "raw", DataHistoryProcessedDetails => "processed", DataHistoryAtTimeDetails => "attime", _ => "unknown",
|
|
};
|
|
|
|
/// <summary>The <c>status_class</c> label of an OPC UA status code (its top two bits).</summary>
|
|
internal static string StatusClass(uint status) => (status >> 30) switch { 0 => "good", 1 => "uncertain", _ => "bad" };
|
|
|
|
private static void Add(Counts counts, uint status)
|
|
{
|
|
switch (status >> 30)
|
|
{
|
|
case 0: Interlocked.Increment(ref counts.Good); break;
|
|
case 1: Interlocked.Increment(ref counts.Uncertain); break;
|
|
default: Interlocked.Increment(ref counts.Bad); break;
|
|
}
|
|
}
|
|
|
|
/// <summary>Counts one answer on the metric only (an origin or gateway built without a diagnostics instance).</summary>
|
|
internal static void Count(string side, string variant, uint status) =>
|
|
Reads.Add(1, new KeyValuePair<string, object?>("variant", variant),
|
|
new KeyValuePair<string, object?>("status_class", StatusClass(status)), new KeyValuePair<string, object?>("side", side));
|
|
|
|
/// <summary>One origin answer to a peer's history item.</summary>
|
|
internal void RecordOriginRead(string variant, uint status)
|
|
{
|
|
Add(_origin, status);
|
|
Count(OriginSide, variant, status);
|
|
}
|
|
|
|
/// <summary>One projected node's answer to a local OPC UA client; <paramref name="connectionId"/> null when unresolved.</summary>
|
|
internal void RecordConsumerRead(string? connectionId, string variant, uint status)
|
|
{
|
|
if (connectionId is not null) Add(_consumer.GetOrAdd(connectionId, static _ => new Counts()), status);
|
|
Count(ConsumerSide, variant, status);
|
|
}
|
|
|
|
/// <summary>A consumer continuation was handed to a local session.</summary>
|
|
internal void ConsumerContinuationOpened(string connectionId) =>
|
|
Interlocked.Increment(ref _consumer.GetOrAdd(connectionId, static _ => new Counts()).Open);
|
|
|
|
/// <summary>A consumer continuation was resumed (its token sent back) or released.</summary>
|
|
internal void ConsumerContinuationSettled(string connectionId)
|
|
{
|
|
if (_consumer.TryGetValue(connectionId, out var counts)) Interlocked.Decrement(ref counts.Open);
|
|
}
|
|
|
|
/// <summary>Connects the origin services whose live state (backend, sessions, open cursors) this reports.</summary>
|
|
internal void AttachOrigin(Func<(bool Available, int Sessions, int Open)> state) => _originState = state;
|
|
|
|
/// <summary>
|
|
/// H4 review: the origin's backend availability BEFORE its data services exist. They are composed on the first peer call
|
|
/// (the composition needs the driver host actor), so until then the evidence is "available/not, no peer traffic yet" —
|
|
/// zero sessions and continuations are facts, not unknowns — instead of null (which means a pre-H4 build).
|
|
/// </summary>
|
|
public void AttachProvisionalOrigin(Func<bool> available) => _provisionalAvailability = available;
|
|
|
|
/// <summary>The consumer evidence for one connection; zeros when it has seen no history traffic.</summary>
|
|
public ConsumerHistoryCounts CaptureConsumer(string connectionId) =>
|
|
_consumer.TryGetValue(connectionId, out var c)
|
|
? new(Interlocked.Read(ref c.Good), Interlocked.Read(ref c.Uncertain), Interlocked.Read(ref c.Bad), Math.Max(0, Volatile.Read(ref c.Open)))
|
|
: new(0, 0, 0, 0);
|
|
|
|
/// <summary>Consumer continuations open across every connection.</summary>
|
|
public int OpenConsumerContinuations => _consumer.Values.Sum(x => Math.Max(0, Volatile.Read(ref x.Open)));
|
|
|
|
/// <summary>
|
|
/// The origin evidence: live once the origin services are attached; before that the provisional "no peer traffic yet"
|
|
/// state when one is attached; otherwise null (no data-connection origin on this node).
|
|
/// </summary>
|
|
public OriginHistoryDiagnostics? CaptureOrigin()
|
|
{
|
|
if (_originState is not { } state)
|
|
{
|
|
if (_provisionalAvailability is not { } provisional) return null;
|
|
try { return new(provisional(), 0, 0, 0, 0, 0, PeerServicesStarted: false); }
|
|
catch (Exception) { return null; }
|
|
}
|
|
(bool Available, int Sessions, int Open) now;
|
|
try { now = state(); }
|
|
catch (Exception) { return null; }
|
|
return new(now.Available, now.Sessions, now.Open, Interlocked.Read(ref _origin.Good), Interlocked.Read(ref _origin.Uncertain),
|
|
Interlocked.Read(ref _origin.Bad));
|
|
}
|
|
}
|