06da40a909
- a sequence gap outside a bracket is a loss (re-refresh, same budget); older/repeated sequence numbers are ignored and not recorded - AlarmInitialStateEventArgs.Withdrawn (additive): the driver withdraws 'known' once per signalled episode on its first loss; DriverHostActor sends MarkConditionsKnown(Known:false) for those conditions, drops them from the backstop and re-arms F5 - a RefreshStart while a bracket is open is a loss (never erases the open bracket's) - a failed ConditionRefresh call is retried through the same bounded retry - retry generation token (a finished retry never clears a newer retry's pending flag) - spent budget renews after a 5-min cool-down; RefreshRequired sweeps coalesced Red/green per fix (7 mutations) + live opc-plc gate re-run.
314 lines
16 KiB
C#
314 lines
16 KiB
C#
using System.Text.Json;
|
||
using Akka.Actor;
|
||
using Akka.TestKit;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using Shouldly;
|
||
using Xunit;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Engines;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.OpcUa;
|
||
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
|
||
|
||
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
|
||
|
||
/// <summary>
|
||
/// A1 (plan §5.1) reusable rig for native "standing alarms delivered" signal tests: a real
|
||
/// <see cref="DriverHostActor"/> + real <see cref="DriverInstanceActor"/> around a
|
||
/// <see cref="FakeSignallingAlarmDriver"/>, with the OPC UA publish actor replaced by a probe so the exact order of
|
||
/// <see cref="OpcUaPublishActor.AlarmStateUpdate"/> and <see cref="OpcUaPublishActor.MarkConditionsKnown"/> is
|
||
/// observable. The driver agent's per-driver tests (ii, iii, vi–ix) inherit this and swap the fake for each real
|
||
/// driver's shape.
|
||
/// </summary>
|
||
public abstract class NativeAlarmSignalTestBase : RuntimeActorTestBase
|
||
{
|
||
/// <summary>The driver instance id the rig deploys.</summary>
|
||
protected const string DriverId = "drv-sig";
|
||
private static readonly NodeId RigNode = NodeId.Parse("a1-signal-rig");
|
||
private static readonly RevisionHash Rev = RevisionHash.Parse(new string('c', 64));
|
||
private IDbContextFactory<OtOpcUaConfigDbContext>? _rigDb;
|
||
private TestProbe? _rigCoordinator;
|
||
private string? _rigDriverType;
|
||
private int _redeploys;
|
||
|
||
/// <summary>The RawPath of alarm tag <paramref name="tag"/> under the rig's folder/driver/device.</summary>
|
||
/// <param name="tag">The tag name.</param>
|
||
/// <returns>The RawPath (= the driver ConditionId = the condition NodeId).</returns>
|
||
protected static string RawPathOf(string tag) => $"Plant/Drv/dev1/{tag}";
|
||
|
||
/// <summary>One started rig.</summary>
|
||
/// <param name="Host">The driver host.</param>
|
||
/// <param name="Publish">The publish-actor probe (rebuild already drained).</param>
|
||
/// <param name="Driver">The fake driver the host spawned.</param>
|
||
/// <param name="Hub">The hub the F5 diagnostic is raised on.</param>
|
||
protected sealed record Rig(IActorRef Host, TestProbe Publish, FakeSignallingAlarmDriver Driver, ConditionStateHub Hub);
|
||
|
||
/// <summary>Deploys <paramref name="alarmTags"/> as native alarm tags of one enabled driver of
|
||
/// <paramref name="driverType"/>, waits for the apply, the driver's connection and its alarm subscription.</summary>
|
||
/// <param name="driverType">The driver type (decides the backstop / F5 timeout).</param>
|
||
/// <param name="alarmTags">The alarm tag names.</param>
|
||
/// <param name="configure">Adjusts the signal options (timeouts).</param>
|
||
/// <param name="driver">A pre-built fake (e.g. with a subscribe delay), or null for a default one.</param>
|
||
/// <returns>The rig.</returns>
|
||
protected Rig StartRig(string driverType, IReadOnlyList<string> alarmTags,
|
||
Func<ConditionSignalOptions, ConditionSignalOptions>? configure = null, FakeSignallingAlarmDriver? driver = null)
|
||
{
|
||
driver ??= new FakeSignallingAlarmDriver(DriverId, driverType);
|
||
var fake = driver;
|
||
var (host, publish, hub) = StartRig(driver, driverType, alarmTags, configure, () => fake.Subscribed);
|
||
return new Rig(host, publish, driver, hub);
|
||
}
|
||
|
||
/// <summary>
|
||
/// The same rig over ANY <see cref="IDriver"/> (a REAL driver over a fake device): deploys
|
||
/// <paramref name="alarmTags"/> on it and waits for the apply, then for <paramref name="ready"/> (e.g. the real
|
||
/// driver's alarm subscription) when given.
|
||
/// </summary>
|
||
/// <param name="driver">The driver the host spawns (its <see cref="IDriver.DriverInstanceId"/> must be <see cref="DriverId"/>).</param>
|
||
/// <param name="driverType">The driver type.</param>
|
||
/// <param name="alarmTags">The alarm tag names (RawPaths per <see cref="RawPathOf"/>).</param>
|
||
/// <param name="configure">Adjusts the signal options (timeouts).</param>
|
||
/// <param name="ready">Optional readiness predicate awaited after the apply.</param>
|
||
/// <returns>The host, the publish probe and the hub.</returns>
|
||
protected (IActorRef Host, TestProbe Publish, ConditionStateHub Hub) StartRig(IDriver driver, string driverType,
|
||
IReadOnlyList<string> alarmTags, Func<ConditionSignalOptions, ConditionSignalOptions>? configure = null,
|
||
Func<bool>? ready = null)
|
||
{
|
||
var db = NewInMemoryDbFactory();
|
||
var deploymentId = Seed(db, driverType, alarmTags, Rev);
|
||
_rigDb = db;
|
||
_rigDriverType = driverType;
|
||
var hub = new ConditionStateHub();
|
||
var options = new ConditionSignalOptions { Hub = hub };
|
||
options = configure?.Invoke(options) ?? options;
|
||
|
||
var coordinator = _rigCoordinator = CreateTestProbe();
|
||
var publish = this.CreateCleanOutcomePublishProbe();
|
||
var host = Sys.ActorOf(DriverHostActor.Props(
|
||
db, RigNode, coordinator.Ref,
|
||
driverFactory: new SingleDriverFactory(driver),
|
||
localRoles: new HashSet<string> { "driver" },
|
||
dependencyMux: CreateTestProbe().Ref,
|
||
opcUaPublishActor: publish.Ref,
|
||
virtualTagEvaluator: NullVirtualTagEvaluator.Instance,
|
||
virtualTagHostOverride: CreateTestProbe().Ref,
|
||
conditionSignals: options));
|
||
|
||
host.Tell(new DispatchDeployment(deploymentId, Rev, CorrelationId.NewId()));
|
||
coordinator.FishForMessage<ApplyAck>(_ => true, TimeSpan.FromSeconds(10), cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||
if (ready is not null) AwaitCondition(ready, TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||
return (host, publish, hub);
|
||
}
|
||
|
||
/// <summary>Re-deploys the last started rig with <paramref name="alarmTags"/> (a new revision) and waits for the apply.</summary>
|
||
/// <param name="rig">The rig.</param>
|
||
/// <param name="alarmTags">The alarm tag names the new revision carries.</param>
|
||
protected void Redeploy(Rig rig, IReadOnlyList<string> alarmTags)
|
||
{
|
||
var rev = RevisionHash.Parse(new string((char)('d' + _redeploys++ % 3), 64));
|
||
var deploymentId = Seed(_rigDb!, _rigDriverType!, alarmTags, rev);
|
||
rig.Host.Tell(new DispatchDeployment(deploymentId, rev, CorrelationId.NewId()));
|
||
_rigCoordinator!.FishForMessage<ApplyAck>(a => a.DeploymentId == deploymentId, TimeSpan.FromSeconds(10),
|
||
cancellationToken: TestContext.Current.CancellationToken).Outcome.ShouldBe(ApplyAckOutcome.Applied);
|
||
}
|
||
|
||
/// <summary>The rig's current driver child (the <c>DriverInstanceActor</c> the host spawned).</summary>
|
||
/// <param name="rig">The rig.</param>
|
||
/// <returns>Its actor ref.</returns>
|
||
protected IActorRef ChildOf(Rig rig) =>
|
||
Sys.ActorSelection(rig.Host.Path + "/drv-*").ResolveOne(TimeSpan.FromSeconds(5)).GetAwaiter().GetResult();
|
||
|
||
/// <summary>Negative control: for <paramref name="duration"/>, the probe receives no
|
||
/// <see cref="OpcUaPublishActor.MarkConditionsKnown"/> that marks known (other traffic — quality annotations,
|
||
/// withdrawals — is ignored).</summary>
|
||
/// <param name="publish">The probe.</param>
|
||
/// <param name="duration">How long to watch.</param>
|
||
protected static void AssertNoMark(TestProbe publish, TimeSpan duration)
|
||
{
|
||
var deadline = DateTime.UtcNow + duration;
|
||
while (DateTime.UtcNow < deadline)
|
||
{
|
||
var m = publish.ReceiveOne(deadline - DateTime.UtcNow);
|
||
if (m is OpcUaPublishActor.MarkConditionsKnown { Known: true } mark)
|
||
throw new ShouldAssertException($"unexpected MarkConditionsKnown({string.Join(",", mark.ConditionIds)})");
|
||
}
|
||
}
|
||
|
||
/// <summary>The publish-actor messages that are alarm-state updates or KNOWN marks (withdrawals skipped), in arrival order, until
|
||
/// <paramref name="until"/> matches (inclusive).</summary>
|
||
/// <param name="publish">The probe.</param>
|
||
/// <param name="until">Stop condition.</param>
|
||
/// <param name="timeout">Overall wait.</param>
|
||
/// <returns>The ordered messages.</returns>
|
||
protected static List<object> CollectAlarmTraffic(TestProbe publish, Func<object, bool> until, TimeSpan? timeout = null)
|
||
{
|
||
var seen = new List<object>();
|
||
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(10));
|
||
while (DateTime.UtcNow < deadline)
|
||
{
|
||
var m = publish.ReceiveOne(deadline - DateTime.UtcNow);
|
||
if (m is null) break;
|
||
if (m is not (OpcUaPublishActor.AlarmStateUpdate or OpcUaPublishActor.MarkConditionsKnown)) continue;
|
||
// Withdrawals (every connectivity edge sends one, review round 2 F1) are not marks.
|
||
if (m is OpcUaPublishActor.MarkConditionsKnown { Known: false }) continue;
|
||
seen.Add(m);
|
||
if (until(m)) return seen;
|
||
}
|
||
|
||
throw new ShouldAssertException($"stop condition not met; saw {seen.Count} alarm message(s)");
|
||
}
|
||
|
||
private static DeploymentId Seed(IDbContextFactory<OtOpcUaConfigDbContext> db, string driverType, IReadOnlyList<string> alarmTags,
|
||
RevisionHash rev)
|
||
{
|
||
var artifact = JsonSerializer.SerializeToUtf8Bytes(new
|
||
{
|
||
RawFolders = new[] { new { RawFolderId = "rf-plant", ParentRawFolderId = (string?)null, Name = "Plant", ClusterId = "c1" } },
|
||
DriverInstances = new[]
|
||
{
|
||
new { DriverInstanceId = DriverId, RawFolderId = "rf-plant", Name = "Drv", DriverType = driverType, DriverConfig = "{}", ClusterId = "c1", Enabled = true },
|
||
},
|
||
Devices = new[] { new { DeviceId = "dev-1", DriverInstanceId = DriverId, Name = "dev1", DeviceConfig = "{}" } },
|
||
TagGroups = Array.Empty<object>(),
|
||
Tags = alarmTags.Select((t, i) => new
|
||
{
|
||
TagId = $"tag-{i}", DeviceId = "dev-1", TagGroupId = (string?)null, Name = t, DataType = "Boolean",
|
||
AccessLevel = 0, TagConfig = JsonSerializer.Serialize(new { alarm = new { alarmType = "OffNormalAlarm", severity = 700 } }),
|
||
}).ToArray(),
|
||
});
|
||
|
||
var id = DeploymentId.NewId();
|
||
using var ctx = db.CreateDbContext();
|
||
ctx.Deployments.Add(new Deployment
|
||
{
|
||
DeploymentId = id.Value, RevisionHash = rev.Value, Status = DeploymentStatus.Sealed, CreatedBy = "test",
|
||
SealedAtUtc = DateTime.UtcNow, ArtifactBlob = artifact,
|
||
});
|
||
ctx.SaveChanges();
|
||
return id;
|
||
}
|
||
|
||
private sealed class SingleDriverFactory(IDriver driver) : IDriverFactory
|
||
{
|
||
public IDriver? TryCreate(string driverType, string driverInstanceId, string driverConfigJson) => driver;
|
||
public IReadOnlyCollection<string> SupportedTypes => [driver.DriverType];
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// A fake native alarm source that obeys the §5.1 contract: alarm events AND the initial-state signal are raised
|
||
/// on the driver's own thread, the signal after the events it covers, and only while an alarm subscription is live
|
||
/// (G5). <see cref="OnSubscribed"/> plays the post-subscribe replay (e.g. Galaxy's snapshot + sentinel).
|
||
/// </summary>
|
||
public sealed class FakeSignallingAlarmDriver(string driverInstanceId, string driverType) : IDriver, IAlarmSource, IAlarmInitialStateSignal
|
||
{
|
||
private volatile bool _subscribed;
|
||
private volatile IReadOnlyList<string> _refs = [];
|
||
|
||
/// <inheritdoc />
|
||
public string DriverInstanceId => driverInstanceId;
|
||
|
||
/// <inheritdoc />
|
||
public string DriverType => driverType;
|
||
|
||
/// <summary>Whether an alarm subscription is live.</summary>
|
||
public bool Subscribed => _subscribed;
|
||
|
||
/// <summary>The refs of the live alarm subscription.</summary>
|
||
public IReadOnlyList<string> SubscribedRefs => _refs;
|
||
|
||
/// <summary>How long <see cref="SubscribeAlarmsAsync"/> holds the <see cref="DriverInstanceActor"/> mailbox AFTER the
|
||
/// subscription went live — the F2 "delay the DriverInstanceActor" lever.</summary>
|
||
public TimeSpan SubscribeDelay { get; init; }
|
||
|
||
/// <summary>Run on a feed thread once a subscription goes live (the post-subscribe replay).</summary>
|
||
public Action<FakeSignallingAlarmDriver>? OnSubscribed { get; set; }
|
||
|
||
/// <inheritdoc />
|
||
public event EventHandler<AlarmEventArgs>? OnAlarmEvent;
|
||
|
||
/// <inheritdoc />
|
||
public event EventHandler<AlarmInitialStateEventArgs>? InitialAlarmStateDelivered;
|
||
|
||
/// <inheritdoc />
|
||
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
|
||
|
||
/// <inheritdoc />
|
||
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) => Task.CompletedTask;
|
||
|
||
/// <inheritdoc />
|
||
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||
|
||
/// <inheritdoc />
|
||
public DriverHealth GetHealth() => new(DriverState.Healthy, null, null);
|
||
|
||
/// <inheritdoc />
|
||
public async Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken)
|
||
{
|
||
_refs = sourceNodeIds;
|
||
_subscribed = true;
|
||
if (OnSubscribed is { } replay) _ = Task.Run(() => replay(this), CancellationToken.None);
|
||
if (SubscribeDelay > TimeSpan.Zero) await Task.Delay(SubscribeDelay, CancellationToken.None).ConfigureAwait(false);
|
||
return new Handle();
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
public Task UnsubscribeAlarmsAsync(IAlarmSubscriptionHandle handle, CancellationToken cancellationToken)
|
||
{
|
||
_subscribed = false;
|
||
return Task.CompletedTask;
|
||
}
|
||
|
||
/// <inheritdoc />
|
||
public Task AcknowledgeAsync(IReadOnlyList<AlarmAcknowledgeRequest> acknowledgements, CancellationToken cancellationToken) =>
|
||
Task.CompletedTask;
|
||
|
||
/// <summary>Drop the subscription (the suppression gate closes).</summary>
|
||
public void Unsubscribe() => _subscribed = false;
|
||
|
||
/// <summary>Raise one alarm transition — a no-op (false) while no subscription is live (G5).</summary>
|
||
/// <param name="conditionId">The ConditionId (= RawPath).</param>
|
||
/// <param name="kind">The transition.</param>
|
||
/// <param name="message">The message.</param>
|
||
/// <returns>Whether it was raised.</returns>
|
||
public bool Raise(string conditionId, AlarmTransitionKind kind = AlarmTransitionKind.Raise, string message = "standing")
|
||
{
|
||
if (!_subscribed) return false;
|
||
OnAlarmEvent?.Invoke(this, new AlarmEventArgs(new Handle(), conditionId, conditionId, "OffNormalAlarm", message,
|
||
AlarmSeverity.High, DateTime.UtcNow, Kind: kind));
|
||
return true;
|
||
}
|
||
|
||
/// <summary>Raise the initial-state signal — a no-op (false) while no subscription is live (G5).</summary>
|
||
/// <param name="conditionIds">The conditions it covers.</param>
|
||
/// <param name="unsignalable">Report InitialStateUnsignalable instead.</param>
|
||
/// <returns>Whether it was raised.</returns>
|
||
public bool Signal(IReadOnlyList<string> conditionIds, bool unsignalable = false, bool withdrawn = false)
|
||
{
|
||
if (!_subscribed) return false;
|
||
InitialAlarmStateDelivered?.Invoke(this, new AlarmInitialStateEventArgs(conditionIds, unsignalable, withdrawn));
|
||
return true;
|
||
}
|
||
|
||
/// <summary>A Galaxy-shaped snapshot: one Raise per standing alarm, then the sentinel signal over every subscribed
|
||
/// condition, all on the calling (feed) thread.</summary>
|
||
/// <param name="standing">The standing (active) conditions.</param>
|
||
public void ReplaySnapshot(IReadOnlyList<string> standing)
|
||
{
|
||
foreach (var id in standing) Raise(id);
|
||
Signal(SubscribedRefs);
|
||
}
|
||
|
||
private sealed class Handle : IAlarmSubscriptionHandle
|
||
{
|
||
public string DiagnosticId => "fake-alarm-sub";
|
||
}
|
||
}
|