feat(grpc-data): H4 remote-history diagnostics and metrics

Consumer and origin history evidence for data connections (plan §6):
- DataConnectionHistoryDiagnostics: otopcua.dataconn.history.reads{variant,status_class,side} and
  otopcua.dataconn.history.continuations.active{side} on the exported OtOpcUa meter (the H2 origin
  counter sat on a private meter the host never exported); the plan's unknown-bits counter is the
  existing X0 otopcua.dataconnection.unknown_operations_dropped, reused
- per-connection projected answers by status class and open consumer continuations (settled on
  resume claim or release); origin sessions, open continuations and answers by status class
- negotiated features and advertised history variants/aggregates per connection
- AdminUI data-connections page renders them plus the dropped unknown-operation bits (#919)
- H4 unit-phase manifest key
This commit is contained in:
Joseph Doherty
2026-11-24 08:01:57 -05:00
parent b1973d6fdd
commit e3f21cb86c
19 changed files with 687 additions and 30 deletions
@@ -35,7 +35,9 @@ else
@if (live.Row.Serving is { } serving) { <span> · serving @serving.NodeId · role @serving.Role · incarnation @serving.Incarnation</span> }
<div>Streams @live.Row.ActiveStreams · calls @live.Row.ActiveCalls · retained import views @Measure(live.Row.SourceCount) · registrations @Measure(live.Row.RegistrationCount) · resets @Measure(live.Row.ResetCount) · coalesced notices @Measure(live.Row.CoalescedCount) · overflows @Measure(live.Row.OverflowCount)</div>
<div>Writes succeeded @Measure(live.Row.WriteSucceededCount) · rejected @Measure(live.Row.WriteRejectedCount) · failed @Measure(live.Row.WriteFailedCount) · unconfirmed @Measure(live.Row.WriteUnconfirmedCount) · unknown @Measure(live.Row.WriteUnknownCount)</div>
<div>Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")</div></div>
<div>Last observed sample bound @Time(live.Row.LastSampleAtUtc) (age upper bound @DataConnectionDiagnostics.SampleAge(live.Row)) · metadata lease expires @Time(live.Row.MetadataLeaseExpiresAtUtc) · last handshake @Time(live.Row.LastVerifiedAtUtc) · observed @live.Row.AsOfUtc.ToString("u") · artifact @live.Row.ArtifactRevision · protocol @(live.Row.ProtocolMajor is { } major && live.Row.ProtocolMinor is { } minor ? $"{major}.{minor}" : "unavailable")</div>
<div class="data-connection-history">Negotiated features @DataConnectionDiagnostics.Features(live.Row.NegotiatedFeatures) · origin history @DataConnectionDiagnostics.HistoryServed(live.Row) · projected history reads @DataConnectionDiagnostics.HistoryCounts(live.Row.HistoryReadsGood, live.Row.HistoryReadsUncertain, live.Row.HistoryReadsBad) · open remote continuations (local sessions) @Measure(live.Row.OpenRemoteContinuations)</div>
<div class="@(DataConnectionDiagnostics.HasDrops(live.Row.DroppedUnknownOperations, live.Row.MappingsWithDroppedOperations) ? "notice data-connection-dropped" : "data-connection-dropped")">Dropped unknown operation bits: connection @DataConnectionDiagnostics.DroppedBits(live.Row.DroppedUnknownOperations) · mappings with dropped bits @Measure(live.Row.MappingsWithDroppedOperations)@if (DataConnectionDiagnostics.HasDrops(live.Row.DroppedUnknownOperations, live.Row.MappingsWithDroppedOperations)) { <span> — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded.</span> }</div></div>
}
@foreach (var applied in _applied.Where(x => Same(x.ConnectionId, row.Id))) { <span class="small">@applied.NodeId: last applied revision @applied.Revision (@(applied.Enabled ? "enabled" : "disabled"))</span> }
@if (row.Draft is { } editable) { <AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-outline-primary" @onclick="() => Edit(editable)">Edit</button></AuthorizeView> }</div>
@@ -43,6 +45,30 @@ else
<AuthorizeView Policy="@AdminUiPolicies.ConfigEditor"><button class="btn btn-sm btn-primary" @onclick="NewConnection">New connection</button></AuthorizeView>
</div>
</section>
<section class="panel mt-3">
<h2 class="panel-head">Origin evidence by node</h2><div class="p-3">
@if (!_nodeSnapshots.Any()) { <p class="text-muted">No node has reported.</p> }
@foreach (var (nodeId, node) in _nodeSnapshots)
{
<div class="small mb-2 data-connection-origin"><strong>@nodeId</strong>
@if (node.OriginHistory is { } origin)
{
<span> · remote history @(origin.Available ? "served" : "no historian backend") · peer history sessions @origin.Sessions · open origin continuations @origin.OpenContinuations · history items answered @DataConnectionDiagnostics.HistoryCounts(origin.ReadsGood, origin.ReadsUncertain, origin.ReadsBad)</span>
}
else { <span> · remote history evidence unavailable</span> }
@if (node.DroppedExportOperations is { } dropped)
{
@if (dropped.Count == 0) { <span> · dropped unknown export bits: none</span> }
else
{
<div class="notice" role="note">Exports with dropped unknown operation bits: @string.Join("; ", dropped.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase).Select(x => $"{x.Key}: {DataConnectionDiagnostics.DroppedBits(x.Value)}")) — this node's build is older than a feature authored here; the dropped bits grant nothing until the node is upgraded.</div>
}
}
else { <span> · dropped unknown export bits unavailable</span> }
</div>
}
</div>
</section>
<section class="panel mt-3">
<h2 class="panel-head">Exports</h2><div class="p-3">
@if (!Exports.Any()) { <p class="text-muted">No export grants have been authored.</p> }
@@ -125,6 +151,7 @@ else
private object? _deleteCandidate;
private IReadOnlyList<AppliedConnection> _applied = [];
private List<(string NodeId, DataConnectionDiagnosticsSnapshot Row)> _live = [];
private List<(string NodeId, NodeDiagnosticsSnapshot Snapshot)> _nodeSnapshots = [];
private IReadOnlyList<ConnectionDisplayRow> ConnectionRows => DataConnectionDiagnostics.Rows(Connections, _applied.Select(x => x.ConnectionId), _live.Select(x => x.Row.ConnectionId));
private IEnumerable<DataConnection> Connections => _snapshot!.DataConnections.Where(x => Same(x.ClusterId, ClusterId));
private IEnumerable<DataExport> Exports => _snapshot!.DataExports.Where(x => Same(x.ClusterId, ClusterId));
@@ -139,6 +166,7 @@ else
try { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)await Diagnostics.GetDiagnosticsAsync(NodeId.Parse($"{node.Host}:{node.AkkaPort}"), CancellationToken.None)); }
catch (Exception) { return (node.NodeId, Snapshot: (NodeDiagnosticsSnapshot?)null); }
}));
_nodeSnapshots = observations.Where(x => x.Snapshot is not null).Select(x => (x.NodeId, x.Snapshot!)).ToList();
_live = observations.Where(x => x.Snapshot?.DataConnections is not null)
.SelectMany(x => x.Snapshot!.DataConnections!.Select(row => (x.NodeId, row))).ToList();
}
@@ -1,4 +1,6 @@
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
@@ -23,6 +25,41 @@ public static class DataConnectionDiagnostics
"disabled" => "Disabled", "connecting" => "Connecting", "ready" => "Ready", "degraded" => "Degraded",
"auth-failed" => "Authentication failed", "backoff" => "Backoff", _ => "Unavailable"
};
/// <summary>H4: the features the last handshake negotiated; "none (v1)" when the peer negotiated nothing optional.</summary>
public static string Features(DataFeatures? features) => features switch
{
null => "unavailable",
DataFeatures.None => "none (v1 behaviour)",
{ } f => string.Join(", ", Enum.GetValues<DataFeatures>().Where(x => x != DataFeatures.None && f.HasFlag(x)).Select(x => x.ToString())
.DefaultIfEmpty($"0x{(int)f:X}")),
};
/// <summary>H4: the history variants and aggregate count the origin advertised to this caller.</summary>
public static string HistoryServed(DataConnectionDiagnosticsSnapshot row) =>
row.HistoryVariants is not { } variants ? "not advertised"
: variants.Count == 0 ? "advertised, no variant granted"
: string.Join(", ", variants) + (row.HistoryAggregateCount is { } n ? $" ({n} aggregates)" : "");
/// <summary>H4: history results by status class, "unavailable" from a node built before H4.</summary>
public static string HistoryCounts(long? good, long? uncertain, long? bad) =>
good is null && uncertain is null && bad is null ? "unavailable"
: $"good {good ?? 0} · uncertain {uncertain ?? 0} · bad {bad ?? 0}";
/// <summary>
/// #919: operation bits a node dropped because its build does not implement them. Named when this AdminUI knows the
/// bit, hex otherwise; "unavailable" from a node built before X0.
/// </summary>
public static string DroppedBits(DataOperations? bits) => bits switch
{
null => "unavailable",
DataOperations.None => "none",
{ } b => string.Join(", ", Enumerable.Range(0, 31).Select(i => (DataOperations)(1 << i)).Where(x => b.HasFlag(x))
.Select(x => Enum.IsDefined(x) ? DataOperationAuthoring.Label(x) : $"0x{(int)x:X}")),
};
/// <summary>#919: true when the drop deserves the "node build is older than the authored feature" hint.</summary>
public static bool HasDrops(DataOperations? bits, int? mappings = null) => bits is { } b && b != DataOperations.None || mappings is > 0;
public static string Endpoint(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri)
&& uri.Scheme == Uri.UriSchemeHttps ? (uri.HostNameType == UriHostNameType.IPv6 ? $"https://[{uri.Host}]{(uri.IsDefaultPort ? "" : $":{uri.Port}")}" : $"https://{uri.IdnHost}{(uri.IsDefaultPort ? "" : $":{uri.Port}")}") : "Unavailable";
}
@@ -118,12 +118,15 @@ public static class DataConnectionRegistration
(!settings.IsWarm || state.WarmRole == WarmRole.Active), state.Generation);
}, renewalSink: sp.GetRequiredService<IProjectedNamespacePageSink>()));
services.AddSingleton<IProjectedDataAccess>(sp => sp.GetRequiredService<ProjectedDataAccess>());
// H4: one dependency-free history diagnostics instance shared by the origin services, the consumer gateway and the
// diagnostics readers (it also backs the otopcua.dataconn.history.* metrics).
services.AddSingleton<DataConnectionHistoryDiagnostics>();
// H3: OPC UA HistoryRead on projected variables, forwarded over the mapping's deployed connection.
services.AddSingleton(sp => new ProjectedHistoryAccess(sp.GetRequiredService<ProjectedDataAccess>(),
sp.GetRequiredService<IGrpcDataAdapterConnectionSource>(),
mappingId => sp.GetRequiredService<ProjectedMappingDeploymentRuntime>().TryGetHistoryAssemblyBudget(mappingId, out var bytes)
? bytes : null,
sp.GetRequiredService<TimeProvider>()));
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataConnectionHistoryDiagnostics>()));
services.AddSingleton<IProjectedHistoryAccess>(sp => sp.GetRequiredService<ProjectedHistoryAccess>());
services.AddSingleton<IConfiguredProjectionDiscovery>(sp => new ConfiguredProjectionDiscovery(
sp.GetRequiredService<ProjectedMappingDeploymentRuntime>(), sp.GetRequiredService<IFederatedProjectionCatalog>(),
@@ -161,7 +164,8 @@ public static class DataConnectionRegistration
options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes,
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)),
// H2: remote history over the node manager's history port, resolved once the SDK server is up.
new DeferredOriginHistoryPort(sp.GetRequiredService<DeferredAddressSpaceSink>()), LoggerFor<LocalDataServices>(sp));
new DeferredOriginHistoryPort(sp.GetRequiredService<DeferredAddressSpaceSink>()), LoggerFor<LocalDataServices>(sp),
sp.GetRequiredService<DataConnectionHistoryDiagnostics>());
});
services.AddSingleton<IDataConnectionFactory>(sp => new DeferredFactory(() => sp.GetRequiredService<LocalDataRuntimeComposition>().Services));
services.AddSingleton<DataConnectionSecretChangeHandler>();
@@ -227,6 +231,7 @@ public static class DataConnectionRegistration
})
{
Logger = LoggerFor<DataConnectionDeploymentRuntime>(sp),
HistoryDiagnostics = sp.GetRequiredService<DataConnectionHistoryDiagnostics>(),
};
return runtime;
});
@@ -53,7 +53,15 @@ public abstract class ProjectedHistoryContinuation
/// <summary>Marks the cursor as handed back for a resume: the resume read owns the origin token from here on.</summary>
/// <returns><c>false</c> when it was already released or resumed.</returns>
public bool TryClaimForResume() => Volatile.Read(ref _released) == 0 && Interlocked.Exchange(ref _claimed, 1) == 0;
public bool TryClaimForResume()
{
if (Volatile.Read(ref _released) != 0 || Interlocked.Exchange(ref _claimed, 1) != 0) return false;
OnClaimed();
return true;
}
/// <summary>Called once when the cursor is claimed for a resume (its origin token is about to be sent back).</summary>
protected virtual void OnClaimed() { }
private void ReleaseOnce()
{
@@ -46,6 +46,8 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
private readonly object _sync = new();
/// <summary>Diagnostics sink for the X0 dropped-operation warning; optional (an init property keeps the constructor shape).</summary>
public ILogger Logger { private get; init; } = NullLogger.Instance;
/// <summary>H4: consumer/origin remote-history evidence merged into the diagnostics; optional (init keeps the constructor shape).</summary>
public DataConnectionHistoryDiagnostics? HistoryDiagnostics { get; init; }
private IReadOnlyDictionary<string, DataOperations> _droppedOperations = new Dictionary<string, DataOperations>();
private long _unknownOperationRows;
private readonly string _node, _owner;
@@ -118,7 +120,18 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
DataOperations? Dropped(string id) => dropped.TryGetValue(id, out var bits) ? bits : DataOperations.None;
int? MappingDrops(string id) => mappingsWithDroppedOperations is null ? null
: mappingsWithDroppedOperations.TryGetValue(id, out var count) ? count : 0;
return desired.Specs.Values.Select(spec =>
var history = HistoryDiagnostics;
ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot WithHistory(
ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot row)
{
if (history is null) return row;
var counts = history.CaptureConsumer(row.ConnectionId);
return row with { HistoryReadsGood = counts.Good, HistoryReadsUncertain = counts.Uncertain, HistoryReadsBad = counts.Bad,
OpenRemoteContinuations = counts.OpenContinuations };
}
return desired.Specs.Values.Select(spec => WithHistory(Capture(spec))).ToArray();
ZB.MOM.WW.OtOpcUa.Commons.Interfaces.DataConnectionDiagnosticsSnapshot Capture(Spec spec)
{
if (!_attemptPending && _scopeReady && _entries.TryGetValue(spec.Id, out var entry) && entry.Ready)
return entry.Connection.CaptureDiagnostics(spec.Revision, desired.ScopeVersion, desired.ArtifactRevision) with
@@ -128,7 +141,7 @@ public sealed class DataConnectionDeploymentRuntime : IAsyncDisposable
_attemptPending ? "connecting" : _retryNotBefore > _clock.GetTimestamp() ? "backoff" : "connecting",
null, null, 0, 0, desired.ScopeVersion, desired.ArtifactRevision, _clock.GetUtcNow().UtcDateTime)
{ DroppedUnknownOperations = Dropped(spec.Id), MappingsWithDroppedOperations = MappingDrops(spec.Id) };
}).ToArray();
}
}
}
@@ -0,0 +1,151 @@
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"/> — one per history item answered, tagged <c>variant</c> (raw | processed | attime),
/// <c>status_class</c> (good | uncertain | bad) and <c>side</c> (origin = served to a peer; consumer = a projected node's
/// answer to a local OPC UA client). 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;
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>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; null until origin services are attached (no data-connection origin on this node yet).</summary>
public OriginHistoryDiagnostics? CaptureOrigin()
{
if (_originState is not { } state) 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));
}
}
@@ -9,6 +9,9 @@ public sealed partial class GrpcDataConnection
private string? _diagnosticEndpoint;
private ServingIdentity? _diagnosticServing;
private int? _diagnosticMajor, _diagnosticMinor;
private DataFeatures? _negotiatedFeatures;
private IReadOnlyList<string>? _historyVariants;
private int? _historyAggregateCount;
private string _diagnosticState = "connecting";
private DateTime? _lastSampleAtUtc, _metadataLeaseExpiresAtUtc, _lastVerifiedAtUtc;
private TimeSpan? _sampleAgeUpper;
@@ -32,7 +35,8 @@ public sealed partial class GrpcDataConnection
SampleAgeUpperBound: ObservedUpperAge(),
CoalescedCount: Interlocked.Read(ref _coalescedCount),
CompactFrameCount: Interlocked.Read(ref _compactFrameCount), FallbackFrameCount: Interlocked.Read(ref _fallbackFrameCount),
SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId);
SerializedValueFrameBytes: Interlocked.Read(ref _serializedValueFrameBytes), AccountingInstanceId: _accountingInstanceId,
NegotiatedFeatures: _negotiatedFeatures, HistoryVariants: _historyVariants, HistoryAggregateCount: _historyAggregateCount);
}
private TimeSpan? ObservedUpperAge()
@@ -50,6 +54,13 @@ public sealed partial class GrpcDataConnection
_diagnosticEndpoint = new UriBuilder(endpoint.Scheme, endpoint.Host, endpoint.Port).Uri.GetLeftPart(UriPartial.Authority);
_diagnosticServing = capabilities.Serving; _lastVerifiedAtUtc = Clock.GetUtcNow().UtcDateTime;
_diagnosticMajor = capabilities.ProtocolMajor; _diagnosticMinor = capabilities.ProtocolMinor;
// H4: what the data calls of this handshake negotiate, and the history the origin advertised to this caller.
_negotiatedFeatures = RequestedFeatures(capabilities);
_historyVariants = capabilities.History is { } history
? new[] { history.Raw ? "raw" : null, history.Processed ? "processed" : null, history.AtTime ? "attime" : null }
.OfType<string>().ToArray()
: null;
_historyAggregateCount = capabilities.History?.Aggregates.Count;
_diagnosticState = capabilities.Readiness == DataReadiness.Ready ? "ready" : "degraded";
}
}
@@ -18,7 +18,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable
public LocalDataRuntimeComposition(LocalCatalogCoordinator catalog, PartitionedSampleHub hub,
DataOperationPolicy policy, DataCapabilitiesProvider capabilities, TimeProvider clock, DataWriteRuntime writes,
IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits,
ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null)
ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null,
DataConnectionHistoryDiagnostics? historyDiagnostics = null)
{
ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub);
ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities);
@@ -38,7 +39,7 @@ public sealed class LocalDataRuntimeComposition : IDisposable
writes: context => writes.ForCaller(context, () => host),
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, _demand, sessionLimits, capacity),
subscriptionFreshnessChallenges: true, history: history)
{ Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance };
{ Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics };
Services = services;
}
public LocalDataServices Services { get; }
@@ -1,4 +1,3 @@
using System.Diagnostics.Metrics;
using System.Globalization;
using System.Text;
using ZB.MOM.WW.OtOpcUa.Commons.DataConnections;
@@ -24,8 +23,21 @@ public sealed partial class LocalDataServices
internal const uint BadContinuationPointInvalid = 0x804A0000u;
private const int ResponseMarginBytes = 64 * 1024;
private static readonly Meter HistoryMeter = new("ZB.MOM.WW.OtOpcUa.DataConnections.History");
private static readonly Counter<long> HistoryReads = HistoryMeter.CreateCounter<long>("otopcua.dataconn.history.reads");
private DataConnectionHistoryDiagnostics? _historyDiagnostics;
/// <summary>
/// H4: where origin history answers are counted and this origin's live history state is reported (diagnostics and the
/// <c>otopcua.dataconn.history.*</c> metrics). Before H4 the counter sat on a private meter the host never exported.
/// </summary>
public DataConnectionHistoryDiagnostics? HistoryDiagnostics
{
get => _historyDiagnostics;
init
{
_historyDiagnostics = value;
value?.AttachOrigin(() => (HistoryServing is not null, HistorySessionCount, HistoryOpenContinuations));
}
}
private readonly IOriginHistoryPort? _history;
private readonly OriginHistorySessions _historySessions;
@@ -442,15 +454,14 @@ public sealed partial class LocalDataServices
private static long SampleBytes(DataHistorySample sample, DataMetadata? catalog) =>
DataHistoryProtoMapper.EncodeSample(sample, catalog).CalculateSize() + 6L;
private static DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results)
private DataHistoryReadResult[] Record(DataHistoryReadRequest request, DataHistoryReadResult[] results)
{
var variant = request.Details switch
{
DataHistoryRawDetails => "raw", DataHistoryProcessedDetails => "processed", DataHistoryAtTimeDetails => "attime", _ => "unknown",
};
var variant = DataConnectionHistoryDiagnostics.Variant(request.Details);
foreach (var result in results)
HistoryReads.Add(1, new KeyValuePair<string, object?>("variant", variant),
new KeyValuePair<string, object?>("status_class", (result.StatusCode >> 30) switch { 0 => "good", 1 => "uncertain", _ => "bad" }));
{
if (_historyDiagnostics is { } diagnostics) diagnostics.RecordOriginRead(variant, result.StatusCode);
else DataConnectionHistoryDiagnostics.Count(DataConnectionHistoryDiagnostics.OriginSide, variant, result.StatusCode);
}
return results;
}
}
@@ -63,15 +63,20 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
/// <param name="connections">The deployed connection registry.</param>
/// <param name="assemblyBudget">A mapping's <c>MaxHistoryAssemblyBytesPerRequest</c>; null = not deployed.</param>
/// <param name="clock">The clock.</param>
/// <param name="diagnostics">H4 per-connection counts and metrics; a private instance when not shared.</param>
public ProjectedHistoryAccess(ProjectedDataAccess access, IGrpcDataAdapterConnectionSource connections,
Func<string, long?> assemblyBudget, TimeProvider clock)
Func<string, long?> assemblyBudget, TimeProvider clock, DataConnectionHistoryDiagnostics? diagnostics = null)
{
Diagnostics = diagnostics ?? new DataConnectionHistoryDiagnostics();
_access = access ?? throw new ArgumentNullException(nameof(access));
_connections = connections ?? throw new ArgumentNullException(nameof(connections));
_assemblyBudget = assemblyBudget ?? throw new ArgumentNullException(nameof(assemblyBudget));
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
}
/// <summary>H4: projected answers by status class and the consumer continuations held in local sessions, per connection.</summary>
public DataConnectionHistoryDiagnostics Diagnostics { get; }
/// <summary>How long a release waits to coalesce with others for the same connection (a session close disposes one by one).</summary>
internal TimeSpan ReleaseCoalesce { get; init; } = TimeSpan.FromMilliseconds(25);
@@ -195,7 +200,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
left -= assembled[i];
}
return outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray();
return Recorded(outcomes.Select(o => o ?? Fail(BadNoCommunication)).ToArray());
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -211,13 +216,21 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
outcomes[i] = Fail(timedOut ? BadTimeout : ex is OperationCanceledException && resumed ? BadContinuationPointInvalid : BadNoCommunication);
}
return outcomes.Select(o => o!).ToArray();
return Recorded(outcomes.Select(o => o!).ToArray());
}
finally
{
foreach (var demand in demands) demand?.Dispose();
}
// H4: one count per node as answered to the local client, attributed to its connection when it resolved to one.
ProjectedHistoryOutcome[] Recorded(ProjectedHistoryOutcome[] answered)
{
var variant = DataConnectionHistoryDiagnostics.Variant(details);
for (var i = 0; i < answered.Length; i++) Diagnostics.RecordConsumerRead(targets[i]?.ConnectionId, variant, answered[i].StatusCode);
return answered;
}
TimeSpan Remaining() => deadline > TimeSpan.Zero
? deadline - _clock.GetElapsedTime(started)
: TimeSpan.FromHours(1); // unbounded locally: the connection's HistoryTimeout still caps each call
@@ -527,11 +540,34 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
private sealed record GroupKey(string ConnectionId, DataHistoryDetails Details, string Resume);
/// <summary>The remote cursor in the consumer's SDK session store (<see cref="HistoryCursorKind"/> <c>Remote</c>).</summary>
private sealed class RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId,
object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId)
: ProjectedHistoryContinuation(realm, localIdentifier)
private sealed class RemoteCursor : ProjectedHistoryContinuation
{
private int _originReleased;
private readonly ProjectedHistoryAccess owner;
private readonly byte[] token;
private readonly string connectionId;
private readonly object? routeIdentity;
private readonly ProjectedHistoryTarget target;
private readonly string callerKey;
private readonly DataHistoryDetails details;
private readonly uint? aggregateId;
private int _originReleased, _settled;
internal RemoteCursor(ProjectedHistoryAccess owner, DataRealm realm, string localIdentifier, byte[] token, string connectionId,
object? routeIdentity, ProjectedHistoryTarget target, string callerKey, DataHistoryDetails details, uint? aggregateId)
: base(realm, localIdentifier)
{
this.owner = owner; this.token = token; this.connectionId = connectionId; this.routeIdentity = routeIdentity;
this.target = target; this.callerKey = callerKey; this.details = details; this.aggregateId = aggregateId;
owner.Diagnostics.ConsumerContinuationOpened(connectionId);
}
/// <summary>H4: open until resumed (the origin consumes the token) or released, whichever comes first.</summary>
private void Settle()
{
if (Interlocked.Exchange(ref _settled, 1) == 0) owner.Diagnostics.ConsumerContinuationSettled(connectionId);
}
protected override void OnClaimed() => Settle();
internal ProjectedHistoryAccess Owner => owner;
internal byte[] Token => token;
internal object? RouteIdentity => routeIdentity;
@@ -546,6 +582,7 @@ public sealed class ProjectedHistoryAccess : IProjectedHistoryAccess, IDisposabl
/// <summary>Releases the origin token (once), whether the cursor was claimed for a resume or not.</summary>
internal void ReleaseOrigin()
{
Settle();
if (Interlocked.Exchange(ref _originReleased, 1) == 0) owner.EnqueueRelease(connectionId, token);
}
@@ -2983,7 +2983,8 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers, IWithUnboundedS
RunningFromCache: _isRunningFromCache,
DataConnections: _dataConnections?.CaptureDiagnostics(_projectedPublisher?.CaptureSourceCounts(),
_catalogCoordinator?.ProjectedMappings?.CaptureDroppedByConnection()),
DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations);
DroppedExportOperations: _catalogCoordinator?.Current?.DroppedUnknownOperations,
OriginHistory: _dataConnections?.HistoryDiagnostics?.CaptureOrigin());
Sender.Tell(snapshot);
}