using System.Diagnostics.Metrics; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.Observability; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; /// /// H4 metrics (plan §6): otopcua.dataconn.history.reads{variant,status_class,side} and /// otopcua.dataconn.history.continuations.active{side} on the exported OtOpcUa meter, no ids in labels; the plan's /// unknown-bit counter is the existing X0 instrument (reused, not duplicated). /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "H4")] public sealed class GrpcDataHistoryMetricsTests { private static readonly string[] AllowedLabels = ["variant", "status_class", "side"]; [Fact] public void History_reads_are_counted_on_the_exported_meter_with_variant_status_class_and_side_only() { var seen = new List<(long Value, Dictionary Tags)>(); using var listener = new MeterListener(); listener.InstrumentPublished = (instrument, l) => { if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == DataConnectionHistoryDiagnostics.ReadsCounterName) l.EnableMeasurementEvents(instrument); }; listener.SetMeasurementEventCallback((_, value, tags, _) => { var map = new Dictionary(); foreach (var tag in tags) map[tag.Key] = tag.Value; lock (seen) seen.Add((value, map)); }); listener.Start(); var diagnostics = new DataConnectionHistoryDiagnostics(); diagnostics.RecordConsumerRead("connection-with-an-id", "processed", 0x40000000u); diagnostics.RecordOriginRead("attime", 0x80720000u); listener.Dispose(); List<(long Value, Dictionary Tags)> snapshot; lock (seen) snapshot = seen.ToList(); // Other tests may count in parallel on the same static counter: assert presence of ours and the label set of all. snapshot.ShouldContain(x => Equals(x.Tags["side"], "consumer") && Equals(x.Tags["variant"], "processed") && Equals(x.Tags["status_class"], "uncertain")); snapshot.ShouldContain(x => Equals(x.Tags["side"], "origin") && Equals(x.Tags["variant"], "attime") && Equals(x.Tags["status_class"], "bad")); foreach (var (value, tags) in snapshot) { value.ShouldBe(1); tags.Keys.OrderBy(x => x).ShouldBe(AllowedLabels.OrderBy(x => x), "no connection, node or principal id in labels"); tags.Values.ShouldNotContain("connection-with-an-id"); } } [Fact] public void Open_continuations_gauge_reports_origin_and_consumer_sides() { var diagnostics = new DataConnectionHistoryDiagnostics(); diagnostics.AttachOrigin(() => (true, 1, 3)); diagnostics.ConsumerContinuationOpened("link"); diagnostics.ConsumerContinuationOpened("link"); var observed = new Dictionary(); using var listener = new MeterListener(); listener.InstrumentPublished = (instrument, l) => { if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && instrument.Name == DataConnectionHistoryDiagnostics.ContinuationsGaugeName) l.EnableMeasurementEvents(instrument); }; listener.SetMeasurementEventCallback((_, value, tags, _) => { foreach (var tag in tags) if (tag.Key == "side") observed[(string)tag.Value!] = value; }); listener.Start(); listener.RecordObservableInstruments(); // Sums across live instances (other tests' instances may add), so at least ours. observed.Keys.OrderBy(x => x).ShouldBe(["consumer", "origin"]); observed["origin"].ShouldBeGreaterThanOrEqualTo(3); observed["consumer"].ShouldBeGreaterThanOrEqualTo(2); GC.KeepAlive(diagnostics); } [Fact] public void Consumer_counts_are_per_connection_case_insensitive_and_settle_never_goes_negative() { var diagnostics = new DataConnectionHistoryDiagnostics(); diagnostics.RecordConsumerRead("Link", "raw", 0); diagnostics.RecordConsumerRead(null, "raw", 0x80000000u); // unresolved node: metric only diagnostics.ConsumerContinuationOpened("link"); diagnostics.ConsumerContinuationSettled("LINK"); diagnostics.ConsumerContinuationSettled("never-opened"); diagnostics.CaptureConsumer("LINK").ShouldBe(new ConsumerHistoryCounts(1, 0, 0, 0)); diagnostics.CaptureConsumer("never-opened").ShouldBe(new ConsumerHistoryCounts(0, 0, 0, 0)); diagnostics.OpenConsumerContinuations.ShouldBe(0); } [Fact] public void Origin_evidence_is_unavailable_until_attached_and_when_the_state_probe_fails() { var diagnostics = new DataConnectionHistoryDiagnostics(); diagnostics.CaptureOrigin().ShouldBeNull(); diagnostics.RecordOriginRead("raw", 0); diagnostics.AttachOrigin(() => (false, 0, 0)); diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(false, 0, 0, 1, 0, 0)); diagnostics.AttachOrigin(() => throw new InvalidOperationException("history port not ready")); diagnostics.CaptureOrigin().ShouldBeNull(); } [Fact] public void Before_any_peer_call_a_provisional_origin_reports_no_peer_traffic_yet_not_unavailable() { // H4 review item 2: the origin services are composed on the first peer call; until then a fresh H4 origin must not // read like a pre-H4 build (null). var diagnostics = new DataConnectionHistoryDiagnostics(); var backend = true; diagnostics.AttachProvisionalOrigin(() => backend); diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(true, 0, 0, 0, 0, 0, NoPeerTrafficYet: true)); backend = false; diagnostics.CaptureOrigin()!.Available.ShouldBeFalse("availability is probed live, not latched"); diagnostics.AttachOrigin(() => (true, 2, 1)); diagnostics.CaptureOrigin().ShouldBe(new ZB.MOM.WW.OtOpcUa.Commons.Interfaces.OriginHistoryDiagnostics(true, 2, 1, 0, 0, 0)); diagnostics.CaptureOrigin()!.NoPeerTrafficYet.ShouldBeFalse(); } [Fact] public void The_plan_unknown_bit_counter_is_the_existing_X0_instrument_not_a_second_one() { // Plan §6 names "…operations.unknown_bits_dropped"; X0 already counts exactly that (one per row per accepted change). UnknownOperationDrops.CounterName.ShouldBe("otopcua.dataconnection.unknown_operations_dropped"); var names = new List(); using var listener = new MeterListener(); listener.InstrumentPublished = (instrument, _) => { if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName) lock (names) names.Add(instrument.Name); }; listener.Start(); _ = new DataConnectionHistoryDiagnostics(); lock (names) names.ShouldNotContain(x => x.Contains("unknown_bits", StringComparison.Ordinal)); } }