82cf7fe155
Co-Authored-By: Claude <noreply@anthropic.com>
121 lines
6.6 KiB
C#
121 lines
6.6 KiB
C#
using System.Diagnostics;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
|
|
|
|
/// <summary>
|
|
/// Plan §9.3 L1 (measured in A4; A1 did not record it): the origin's <c>SnapshotConditions</c> <c>Lock</c> hold inside a
|
|
/// running SDK server with 1,000 conditions in scope while "drivers publish" (two threads writing variable values and alarm
|
|
/// transitions through the node manager's own <c>WriteValue</c> / <c>WriteAlarmCondition</c>, which take <c>Lock</c>).
|
|
/// Pass: hold p99 ≤ 10 ms and no publish delayed > 50 ms during a snapshot. Opt-in (<c>OTOPCUA_L1=1</c>): it is a timing
|
|
/// measurement, not a unit test.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The hold is measured from INSIDE <c>Lock</c>: the <see cref="OtOpcUaNodeManager.OnConditionSnapshotKeysEnumerated"/> hook
|
|
/// marks the start of the off-Lock key enumeration's end, and <see cref="OtOpcUaNodeManager.OnConditionSnapshotHold"/> runs
|
|
/// right after the hold is released; the interval is therefore an UPPER bound of the hold (it also contains the slice's
|
|
/// list allocation and the lock acquisition wait). 1,000 conditions = one hold at <c>DefaultMaxConditionsPerHold</c>.
|
|
/// </remarks>
|
|
[Trait("Feature", "GrpcData")]
|
|
[Trait("Phase", "A4")]
|
|
[Trait("Category", "Perf")]
|
|
public sealed class ConditionSnapshotLockHoldMeasurementTests : IDisposable
|
|
{
|
|
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
|
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-l1-{Guid.NewGuid():N}");
|
|
|
|
[Fact]
|
|
public async Task L1_snapshot_lock_hold_with_1000_conditions_while_publishing()
|
|
{
|
|
Assert.SkipUnless(Environment.GetEnvironmentVariable("OTOPCUA_L1") == "1", "opt-in timing harness (OTOPCUA_L1=1)");
|
|
var started = await OpcUaHostStart.StartAsync(
|
|
port => new OpcUaApplicationHost(
|
|
new OpcUaApplicationHostOptions
|
|
{
|
|
ApplicationName = "OtOpcUa.L1", ApplicationUri = $"urn:OtOpcUa.L1:{Guid.NewGuid():N}", OpcUaPort = port,
|
|
PublicHostname = "localhost", PkiStoreRoot = _pkiRoot,
|
|
},
|
|
Microsoft.Extensions.Logging.Abstractions.NullLogger<OpcUaApplicationHost>.Instance),
|
|
() => new OtOpcUaSdkServer(), Ct);
|
|
var nm = started.Server.NodeManager!;
|
|
nm.ConditionStateSink = new RecordingConditionSink();
|
|
const int Conditions = 1000, Variables = 500;
|
|
for (var d = 0; d < 10; d++)
|
|
{
|
|
var device = $"Plant/dev{d}";
|
|
nm.EnsureFolder(device, null, $"dev{d}", AddressSpaceRealm.Raw);
|
|
for (var i = 0; i < Conditions / 10; i++)
|
|
nm.MaterialiseAlarmCondition($"{device}/Alarm{i}", device, $"Alarm{i}", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
|
for (var i = 0; i < Variables / 10; i++)
|
|
nm.EnsureVariable($"{device}/Tag{i}", device, $"Tag{i}", "Double", false, AddressSpaceRealm.Raw);
|
|
}
|
|
nm.CompleteAddressSpaceApply();
|
|
|
|
long enumerated = 0;
|
|
var holds = new List<double>();
|
|
nm.OnConditionSnapshotKeysEnumerated = () => Volatile.Write(ref enumerated, Stopwatch.GetTimestamp());
|
|
nm.OnConditionSnapshotHold = count =>
|
|
{
|
|
count.ShouldBe(Conditions);
|
|
holds.Add(Stopwatch.GetElapsedTime(Volatile.Read(ref enumerated)).TotalMilliseconds);
|
|
};
|
|
|
|
using var stop = new CancellationTokenSource();
|
|
var publishLatencies = new List<double>[2] { [], [] };
|
|
var publishers = Enumerable.Range(0, 2).Select(p => Task.Run(() =>
|
|
{
|
|
var random = new Random(p);
|
|
var n = 0;
|
|
while (!stop.IsCancellationRequested)
|
|
{
|
|
var device = $"Plant/dev{random.Next(10)}";
|
|
var t = Stopwatch.GetTimestamp();
|
|
if (p == 0) nm.WriteValue($"{device}/Tag{random.Next(Variables / 10)}", (double)n++, 0, DateTime.UtcNow, AddressSpaceRealm.Raw);
|
|
else nm.WriteAlarmCondition($"{device}/Alarm{random.Next(Conditions / 10)}",
|
|
new AlarmConditionSnapshot(Active: (n++ & 1) == 0, Acknowledged: false, Confirmed: true, Enabled: true,
|
|
Shelving: AlarmShelvingKind.Unshelved, Severity: 700, Message: "hi", StatusCode: OpcUaStatus.Good, ConditionClass: null),
|
|
DateTime.UtcNow, AddressSpaceRealm.Raw);
|
|
publishLatencies[p].Add(Stopwatch.GetElapsedTime(t).TotalMilliseconds);
|
|
Thread.SpinWait(2000);
|
|
}
|
|
})).ToArray();
|
|
|
|
for (var i = 0; i < 20; i++) nm.SnapshotConditions((_, _) => true); // warm-up
|
|
holds.Clear();
|
|
foreach (var list in publishLatencies) lock (list) { }
|
|
const int Samples = 500;
|
|
for (var i = 0; i < Samples; i++)
|
|
{
|
|
nm.SnapshotConditions((_, _) => true);
|
|
await Task.Delay(2, Ct);
|
|
}
|
|
stop.Cancel();
|
|
await Task.WhenAll(publishers);
|
|
|
|
static double P(List<double> xs, double q) { var s = xs.OrderBy(x => x).ToArray(); return s[Math.Clamp((int)Math.Ceiling(q * s.Length) - 1, 0, s.Length - 1)]; }
|
|
var writes = publishLatencies[0];
|
|
var alarms = publishLatencies[1];
|
|
TestContext.Current.SendDiagnosticMessage(
|
|
$"L1 holds n={holds.Count} p50={P(holds, .5):F3} p99={P(holds, .99):F3} max={holds.Max():F3} ms; " +
|
|
$"WriteValue n={writes.Count} p99={P(writes, .99):F3} max={writes.Max():F3} ms; " +
|
|
$"WriteAlarmCondition n={alarms.Count} p99={P(alarms, .99):F3} max={alarms.Max():F3} ms");
|
|
var line = $"L1 holds n={holds.Count} p50={P(holds, .5):F3} p99={P(holds, .99):F3} max={holds.Max():F3} ms; " +
|
|
$"WriteValue n={writes.Count} p50={P(writes, .5):F3} p99={P(writes, .99):F3} max={writes.Max():F3} ms; " +
|
|
$"WriteAlarmCondition n={alarms.Count} p50={P(alarms, .5):F3} p99={P(alarms, .99):F3} max={alarms.Max():F3} ms";
|
|
if (Environment.GetEnvironmentVariable("OTOPCUA_L1_OUT") is { Length: > 0 } output) File.AppendAllText(output, line + Environment.NewLine);
|
|
holds.Count.ShouldBe(Samples);
|
|
P(holds, .99).ShouldBeLessThanOrEqualTo(10.0, "L1: snapshot Lock hold p99 ≤ 10 ms");
|
|
writes.Max().ShouldBeLessThanOrEqualTo(50.0, "L1: no data publish delayed > 50 ms");
|
|
await started.Host.DisposeAsync();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
try { if (Directory.Exists(_pkiRoot)) Directory.Delete(_pkiRoot, recursive: true); } catch (IOException) { }
|
|
}
|
|
}
|