9adadd14b4
Co-Authored-By: Claude <noreply@anthropic.com>
183 lines
10 KiB
C#
183 lines
10 KiB
C#
using System.Diagnostics.Metrics;
|
|
using System.Text;
|
|
using Akka.TestKit.Xunit;
|
|
using Newtonsoft.Json.Linq;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
|
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
|
|
|
|
/// <summary>
|
|
/// A4 (plan §6): the condition metrics carry <c>side</c> and never an id; the origin evidence (open items, the item nearest its
|
|
/// limit, snapshot time, resyncs, capacity, unsignalled, method outcomes).
|
|
/// </summary>
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A4")]
|
|
public sealed class GrpcDataConditionDiagnosticsTests
|
|
{
|
|
private static readonly Dictionary<string, string[]> AllowedLabels = new()
|
|
{
|
|
["otopcua.dataconn.conditions.items"] = ["side"],
|
|
["otopcua.dataconn.conditions.resyncs"] = ["side"],
|
|
["otopcua.dataconn.conditions.capacity_rejections"] = ["side"],
|
|
[DataConnectionConditionDiagnostics.RefreshRequiredCounterName] = ["side"],
|
|
["otopcua.dataconn.condition_methods"] = ["method", "outcome", "side"],
|
|
};
|
|
|
|
[Fact]
|
|
public void Every_condition_instrument_is_on_the_exported_meter_with_side_and_no_id()
|
|
{
|
|
var seen = new List<(string Instrument, Dictionary<string, object?> Tags)>();
|
|
using var listener = new MeterListener();
|
|
listener.InstrumentPublished = (instrument, l) =>
|
|
{
|
|
if (instrument.Meter.Name == OtOpcUaTelemetry.MeterName && AllowedLabels.ContainsKey(instrument.Name)) l.EnableMeasurementEvents(instrument);
|
|
};
|
|
listener.SetMeasurementEventCallback<long>((instrument, _, tags, _) =>
|
|
{
|
|
var map = new Dictionary<string, object?>();
|
|
foreach (var tag in tags) map[tag.Key] = tag.Value;
|
|
lock (seen) seen.Add((instrument.Name, map));
|
|
});
|
|
listener.Start();
|
|
|
|
var d = new DataConnectionConditionDiagnostics();
|
|
d.ConsumerRefreshRequired("connection-with-an-id");
|
|
d.ConsumerResync("connection-with-an-id");
|
|
d.ConsumerCapacityRejection("connection-with-an-id");
|
|
d.ConsumerMethod("connection-with-an-id", DataConditionMethods.Acknowledge, DataWriteState.DriverConfirmedSuccess);
|
|
var item = new Item(10, 1000);
|
|
d.OriginItemOpened(item);
|
|
d.OriginResync();
|
|
d.OriginCapacityRejection();
|
|
d.OriginMethod(DataConditionMethods.Confirm, DataWriteState.RejectedBeforeDispatch);
|
|
d.OriginItemClosed(item);
|
|
listener.Dispose();
|
|
|
|
List<(string Instrument, Dictionary<string, object?> Tags)> snapshot;
|
|
lock (seen) snapshot = seen.ToList();
|
|
foreach (var name in AllowedLabels.Keys) snapshot.ShouldContain(x => x.Instrument == name, name);
|
|
snapshot.ShouldContain(x => x.Instrument == "otopcua.dataconn.conditions.items" && Equals(x.Tags["side"], "origin"));
|
|
snapshot.ShouldContain(x => x.Instrument == "otopcua.dataconn.conditions.resyncs" && Equals(x.Tags["side"], "consumer"));
|
|
snapshot.ShouldContain(x => x.Instrument == "otopcua.dataconn.condition_methods" && Equals(x.Tags["side"], "consumer")
|
|
&& Equals(x.Tags["method"], "Acknowledge") && Equals(x.Tags["outcome"], "DriverConfirmedSuccess"));
|
|
snapshot.ShouldContain(x => x.Instrument == "otopcua.dataconn.condition_methods" && Equals(x.Tags["side"], "origin")
|
|
&& Equals(x.Tags["method"], "Confirm"));
|
|
// Other tests may count in parallel on the same static instruments: assert the label set of all.
|
|
foreach (var (instrument, tags) in snapshot)
|
|
{
|
|
tags.Keys.OrderBy(x => x).ShouldBe(AllowedLabels[instrument].OrderBy(x => x), instrument + ": no connection, node or principal id");
|
|
tags.Values.ShouldNotContain("connection-with-an-id");
|
|
}
|
|
}
|
|
|
|
[Fact]
|
|
public void Origin_evidence_reports_open_items_the_item_nearest_its_limit_snapshot_time_unsignalled_and_method_classes()
|
|
{
|
|
var d = new DataConnectionConditionDiagnostics();
|
|
d.CaptureOrigin().ShouldBe(new OriginConditionDiagnostics(0, 0, 0, null, 0, 0, null, new ConditionMethodCounts(0, 0, 0, 0)),
|
|
"zeros (not null) before any peer; no hub attached ⇒ unsignalled unavailable");
|
|
d.AttachUnsignalled(() => 4);
|
|
var big = new Item(600, 1000); // 60 %
|
|
var near = new Item(90, 100); // 90 % — the one to show
|
|
d.OriginItemOpened(big);
|
|
d.OriginItemOpened(near);
|
|
d.OriginSnapshot(new DateTime(2026, 11, 24, 12, 0, 0, DateTimeKind.Utc).Ticks);
|
|
d.OriginResync();
|
|
d.OriginCapacityRejection();
|
|
d.OriginMethod(DataConditionMethods.Acknowledge, DataWriteState.DriverConfirmedSuccess);
|
|
d.OriginMethod(DataConditionMethods.Acknowledge, DataWriteState.RejectedBeforeDispatch);
|
|
d.OriginMethod(DataConditionMethods.AddComment, DataWriteState.DriverConfirmedFailure);
|
|
d.OriginMethod(DataConditionMethods.Confirm, DataWriteState.OutcomeUnknown);
|
|
|
|
var origin = d.CaptureOrigin();
|
|
origin.OpenItems.ShouldBe(2);
|
|
(origin.LargestListing, origin.ListingLimit).ShouldBe((90, 100));
|
|
origin.LastSnapshotAtUtc.ShouldBe(new DateTime(2026, 11, 24, 12, 0, 0, DateTimeKind.Utc));
|
|
(origin.Resyncs, origin.CapacityRejections, origin.UnsignalledConditions).ShouldBe((1L, 1L, (int?)4));
|
|
origin.Methods.ShouldBe(new ConditionMethodCounts(1, 1, 1, 1));
|
|
d.OriginItemClosed(near);
|
|
d.OriginItemClosed(near); // idempotent
|
|
d.CaptureOrigin().OpenItems.ShouldBe(1);
|
|
(d.CaptureOrigin().LargestListing, d.CaptureOrigin().ListingLimit).ShouldBe((600, 1000));
|
|
}
|
|
|
|
[Fact]
|
|
public void Consumer_evidence_is_null_without_an_attached_runtime_and_counts_are_per_connection_case_insensitively()
|
|
{
|
|
var d = new DataConnectionConditionDiagnostics();
|
|
d.CaptureConsumer("link").ShouldBeNull("no consumer runtime ⇒ no condition evidence");
|
|
d.AttachConsumer(id => id == "link" ? new DataConnectionConditionDiagnostics.ConsumerState("live", null, 3, 1,
|
|
[new ConditionMappingDiagnostics("map-a", "Complete", 3, 1000)], 3, 2500) : null);
|
|
d.ConsumerRefreshRequired("LINK");
|
|
d.ConsumerMethod("link", DataConditionMethods.Acknowledge, DataWriteState.AcceptedUnconfirmed);
|
|
var row = d.CaptureConsumer("link").ShouldNotBeNull();
|
|
(row.StreamState, row.Materialised, row.StateUnknown, row.RefreshRequired).ShouldBe(("live", 3, 1, 1L));
|
|
row.Methods.ShouldBe(new ConditionMethodCounts(0, 0, 0, 1), "AcceptedUnconfirmed is not a confirmed success");
|
|
d.CaptureConsumer("other").ShouldBeNull();
|
|
}
|
|
|
|
private sealed class Item(int total, int limit) : DataConnectionConditionDiagnostics.IOriginItem
|
|
{
|
|
public int Total => total;
|
|
public int Limit => limit;
|
|
public long LastSnapshotTicks => 0;
|
|
}
|
|
}
|
|
|
|
/// <summary>A4: the condition members survive the cluster serializer (Akka default JSON) and an older payload decodes them null.</summary>
|
|
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A4")]
|
|
public sealed class GrpcDataConditionDiagnosticsSerializationTests : TestKit
|
|
{
|
|
private static NodeDiagnosticsSnapshot Snapshot() => new(
|
|
// Arrays, as production builds them (a collection expression typed IReadOnlyList<T> does not deserialize — H4).
|
|
NodeId.Parse("consumer-1:4053"), null, Array.Empty<DriverInstanceDiagnostics>(), new DateTime(2026, 11, 24, 13, 0, 0, DateTimeKind.Utc),
|
|
DataConnections: new[]
|
|
{
|
|
new DataConnectionDiagnosticsSnapshot("link", 3, "ready", "https://source-2:4057", null, 0, 0, 7, "artifact-7",
|
|
new DateTime(2026, 11, 24, 13, 0, 0, DateTimeKind.Utc),
|
|
Conditions: new ConsumerConditionDiagnostics("live", new DateTime(2026, 11, 24, 12, 59, 0, DateTimeKind.Utc), 12, 2, 3, 4, 1,
|
|
new[] { new ConditionMappingDiagnostics("map-a", "Complete", 12, 1000), new ConditionMappingDiagnostics("map-b", "Unavailable", 0, 1000, "Denied") },
|
|
12, 2500, new ConditionMethodCounts(5, 1, 0, 2))),
|
|
},
|
|
OriginConditions: new OriginConditionDiagnostics(2, 800, 1000, new DateTime(2026, 11, 24, 12, 58, 0, DateTimeKind.Utc), 1, 0, 3,
|
|
new ConditionMethodCounts(4, 2, 1, 0)));
|
|
|
|
private (Akka.Serialization.Serializer Serializer, string Manifest) SerializerFor(object message)
|
|
{
|
|
var serializer = Sys.Serialization.FindSerializerFor(message);
|
|
return (serializer, Akka.Serialization.Serialization.ManifestFor(serializer, message));
|
|
}
|
|
|
|
[Fact]
|
|
public void A_snapshot_with_the_A4_members_round_trips_on_the_cluster_serializer()
|
|
{
|
|
var message = Snapshot();
|
|
var (serializer, manifest) = SerializerFor(message);
|
|
var round = (NodeDiagnosticsSnapshot)Sys.Serialization.Deserialize(serializer.ToBinary(message), serializer.Identifier, manifest);
|
|
round.OriginConditions.ShouldBe(message.OriginConditions);
|
|
var c = round.DataConnections.ShouldNotBeNull().ShouldHaveSingleItem().Conditions.ShouldNotBeNull();
|
|
var expected = message.DataConnections![0].Conditions!;
|
|
c.ShouldBe(expected with { Mappings = c.Mappings }, "every scalar member survives");
|
|
c.Mappings.ShouldBe(expected.Mappings);
|
|
}
|
|
|
|
[Fact]
|
|
public void An_older_payload_without_the_A4_members_decodes_them_unavailable()
|
|
{
|
|
var message = Snapshot();
|
|
var (serializer, manifest) = SerializerFor(message);
|
|
var json = JObject.Parse(Encoding.UTF8.GetString(serializer.ToBinary(message)));
|
|
json.Remove("OriginConditions").ShouldBeTrue("the A4 node member is on the wire");
|
|
json.Descendants().OfType<JObject>().Single(o => o.ContainsKey("ConnectionId")).Remove("Conditions").ShouldBeTrue();
|
|
var legacy = (NodeDiagnosticsSnapshot)Sys.Serialization.Deserialize(Encoding.UTF8.GetBytes(json.ToString(Newtonsoft.Json.Formatting.None)),
|
|
serializer.Identifier, manifest);
|
|
legacy.OriginConditions.ShouldBeNull();
|
|
legacy.DataConnections.ShouldNotBeNull().ShouldHaveSingleItem().Conditions.ShouldBeNull();
|
|
}
|
|
}
|