Compare commits

...

7 Commits

Author SHA1 Message Date
Joseph Doherty fa2388eabf test(alarms): assert reconnect-dropped native alarm does not dead-letter; tighten severity doc
v2-ci / build (push) Failing after 38s
v2-ci / unit-tests (tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests) (push) Has been skipped
v2-ci / unit-tests (tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests) (push) Has been skipped
v2-ci / integration (tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests) (push) Has been skipped
Add AllDeadLetters probe to Native_alarm_during_reconnect_is_dropped_not_forwarded so the
test genuinely guards the Reconnecting state's Receive<NativeAlarmRaised> drop handler —
removing that handler would now cause a dead-letter and fail the assertion (false-negative
gap closed). Reword the ScriptedAlarms.md severity-mapping note: "snaps on the first
transition" → "every transition maps … overriding the authored seed from the first
transition onward", clarifying that MapSeverity runs on every event, not just the first.
2026-06-14 22:56:18 -04:00
Joseph Doherty c03361de1b test(drivers): extract shared stub-driver harness (de-dup) 2026-06-14 22:49:26 -04:00
Joseph Doherty d8129e5ab7 test(alarms): fix reconnect-drop test to use mailbox-ordering approach 2026-06-14 22:48:36 -04:00
Joseph Doherty 49d98cba31 docs(alarms): note native-alarm severity-bucket snapping 2026-06-14 22:41:57 -04:00
Joseph Doherty 51cda2c744 test(alarms): assert OperatorComment flows through ForwardNativeAlarm 2026-06-14 22:41:43 -04:00
Joseph Doherty c8db5767ea test(alarms): guard native-alarm-during-reconnect is dropped not dead-lettered 2026-06-14 22:41:08 -04:00
Joseph Doherty a1d333869e docs(plans): residual-followups-cleanup plan (4 offline items; reconcile stale residuals) 2026-06-14 22:38:42 -04:00
8 changed files with 436 additions and 229 deletions
+30
View File
@@ -142,6 +142,36 @@ ObjectType. `severity` seeds the condition's initial severity at materialisation
the driver's live alarm events may carry a different severity that overrides it at
runtime.
#### Severity mapping
The authored `severity` (1–1000) seeds the OPC UA condition node at materialisation
time. Every native transition maps the driver's `AlarmSeverity` to one of four fixed
buckets via `NativeAlarmProjector.MapSeverity`, overriding the authored `severity` seed
from the first transition onward:
| `AlarmSeverity` enum | Projected value |
|---|---|
| `Low` | 200 |
| `Medium` | 500 |
| `High` | 700 |
| `Critical` | 900 |
| *(default/unspecified)* | 500 |
That projected integer is then mapped to the OPC UA SDK `EventSeverity` enum
by `OtOpcUaNodeManager.MapSeverity` on each `AlarmStateUpdate` write:
| Projected value range | `EventSeverity` |
|---|---|
| < 200 | `Low` |
| 200 – 399 | `MediumLow` |
| 400 – 599 | `Medium` |
| 600 – 799 | `MediumHigh` |
| ≥ 800 | `High` |
Consequently the four authored buckets land as: Low→`MediumLow`, Medium→`Medium`,
High→`MediumHigh`, Critical→`High`. The authored `severity` field is overridden by
live driver events on every transition.
### Runtime flow
The driver's live `IAlarmSource.OnAlarmEvent` is the sole input. Transition kinds
@@ -0,0 +1,120 @@
# Residual Follow-ups Cleanup Implementation Plan
> **For Claude:** Execute task-by-task via superpowers-extended-cc:subagent-driven-development.
**Goal:** Close the remaining offline-doable, non-blocking residual follow-ups from `pending.md` sections 1–3 (write-pipeline / Phase B native alarms / Galaxy driver nits), and reconcile `pending.md` to record the ones already implemented.
**Architecture:** Pure test + doc work. **No production code changes.** Three new/extended unit tests, one doc note, one test-harness de-dup refactor. All under `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/` + `docs/`.
**Tech stack:** xUnit + Shouldly, Akka.TestKit, .NET 10.
**Branch:** `feat/residual-followups-cleanup` off master `cd20c3c0`.
## Reconciliation finding (why this plan is small)
A grounding sweep (3 read-only Explore agents + direct verification) found that **most** of the
pending.md residuals were already implemented in the harden-milestone-1b / write-outcome / `f05b5d79`
commits. Already-done (verified, no work):
- **WP (a)** stale/reconnecting writes fast-fail — `DriverHostActor.cs:661` (`Receive<RouteNodeWrite>`), `DriverInstanceActor.cs:229,316` (`Receive<WriteAttribute>`).
- **WP (b)** `ExecuteSynchronously` already dropped (`DriverHostActor.cs:630` uses `TaskContinuationOptions.None`); `driverIds` forward-map is already a `HashSet` (`DeploymentArtifact.cs:285`).
- **WP (c)** FOCAS address parse already cached via `GetOrAdd` (`FocasDriver.cs:247`); only the unavoidable first-write parse remains.
- **WP (d)** raw-protocol-blob write test already exists (`Primary_routes_write_for_raw_protocol_blob_tag`).
- **WP (e)** `[InlineData(2, false)]` future-enum trap already in `ParseComposition_maps_numeric_AccessLevel_to_Writable`.
- **Galaxy (1)** `_itemHandles` + `_supervisedHandles` already cleared on reconnect — `GatewayGalaxyDataWriter.InvalidateHandleCaches()` clears both, called from `GalaxyDriver.ReopenAsync()`.
- **Galaxy (2)** `SubscriptionEstablished` self-Tell already handled (debug-swallow) in all three `DriverInstanceActor` states (`:253,:301,:336`).
Genuinely open + offline → the four tasks below. (Live `/run` and live-gw-only integration checks are out of scope per the request.)
---
### Task 1: Phase B (a) — regression test: native alarm during Reconnecting is dropped
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** Task 2, Task 3, Task 4 (disjoint files; but execute serially to avoid concurrent-commit races)
**Files:**
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorNativeAlarmTests.cs`
**Context:** `DriverInstanceActor` in `Connecting`/`Reconnecting` explicitly drops `NativeAlarmRaised` with a debug log (`DriverInstanceActor.cs:262, :345`) so it never dead-letters; only `Connected` forwards it to the parent as `AttributeAlarmPublished` (`:298`). The production behaviour exists; there is no regression test guarding it. The `DetachSubscription` doc-comment (`:499`) already documents the data-change + native-alarm teardown coupling — no doc change needed.
**Steps:**
1. Read the existing test file to reuse its harness (the alarm-source stub driver, the parent `TestProbe`, and the helper that drives the actor into a given state). Note how existing tests (`Native_alarm_is_forwarded_to_parent_as_AttributeAlarmPublished`, `Reconnect_does_not_double_attach_alarm_handler`) construct the actor and force `Reconnecting`.
2. Add a test `Native_alarm_during_reconnect_is_dropped_not_forwarded`: drive the actor into `Reconnecting` (e.g. start it failing init / force-reconnect), `Tell` it a `NativeAlarmRaised`, and assert the parent probe receives **no** `AttributeAlarmPublished` within a short window (`ExpectNoMsg`), and the actor is still alive (no crash / restart).
3. Run: `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DriverInstanceActorNativeAlarm"` — expect green.
4. Commit `test(alarms): guard native-alarm-during-reconnect is dropped not dead-lettered`.
**Acceptance:** new test passes; asserts no forward + actor survives. No production file touched.
---
### Task 2: Phase B (b) — test: OperatorComment flows through ForwardNativeAlarm
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** Task 1, 3, 4 (serial execution)
**Files:**
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorNativeAlarmTests.cs`
**Context:** `DriverHostActor.ForwardNativeAlarm` (`DriverHostActor.cs:519`) publishes an `AlarmTransitionEvent` to the alerts topic with `Comment: msg.Args.OperatorComment` and `User: msg.Args.OperatorComment is null ? string.Empty : "device"`. `AlarmEventArgs.OperatorComment` (`IAlarmSource.cs`) and `AlarmTransitionEvent.Comment` (`Messages/Alerts/AlarmTransitionEvent.cs`) both carry it. No existing test asserts the comment propagates.
**Steps:**
1. Read the existing test file to reuse its harness (Primary node setup, alerts-topic `TestProbe`/mediator, the `AttributeAlarmPublished` construction + alarm-node-id registration that existing tests like `Secondary_node_suppresses_alerts_publish_but_still_updates_condition` use).
2. Add a test `Native_alarm_operator_comment_flows_to_transition_event`: construct an `AttributeAlarmPublished` whose `Args.OperatorComment = "investigating"`, route it through the Primary host, and assert the published `AlarmTransitionEvent.Comment == "investigating"` and `.User == "device"`.
3. Run: `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DriverHostActorNativeAlarm"` — expect green.
4. Commit `test(alarms): assert OperatorComment flows through ForwardNativeAlarm`.
**Acceptance:** new test passes asserting `Comment` + `User` propagation. No production file touched.
---
### Task 3: Phase B (c) — doc note on severity-bucket snapping
**Classification:** trivial
**Estimated implement time:** ~3 min
**Parallelizable with:** Task 1, 2, 4 (serial execution)
**Files:**
- Doc: `docs/ScriptedAlarms.md`
**Context:** Authored native-alarm severity (1..1000) seeds the condition at materialise time, but on the **first transition** it snaps to a 4-bucket value via `NativeAlarmProjector.MapSeverity` (Low→200, Medium→500, High→700, Critical→900; default→500). That projected value is then mapped to SDK `EventSeverity` brackets by `OtOpcUaNodeManager.MapSeverity` (`<200`=Low, `<400`=MediumLow, `<600`=Medium, `<800`=MediumHigh, `≥800`=High) for the Part 9 node's `Severity` attribute.
**Steps:**
1. In the "Native driver alarms (equipment-tag path)" section (after the `severity` field description, ~line 143), add a short **Severity mapping** note describing the snap: authored severity seeds the condition; the first transition snaps it to one of 200/500/700/900; that bucket then maps to the SDK `EventSeverity` brackets. Reference `NativeAlarmProjector.MapSeverity`.
2. Commit `docs(alarms): note native-alarm severity-bucket snapping`.
**Acceptance:** doc note is accurate to the two mapping tables; no behaviour change.
---
### Task 4: Galaxy (3) — extract shared stub-driver test harness
**Classification:** small
**Estimated implement time:** ~5 min
**Parallelizable with:** Task 1, 2, 3 (serial execution)
**Files:**
- Create: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/StubDrivers.cs`
- Modify: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorTests.cs` (remove the private nested stub classes, ~lines 325–462)
- Modify: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorWriteAndSubscribeTests.cs` (remove the private nested stub classes, ~lines 178–312)
**Context:** Both files define their own `StubDriver : IDriver`, `WritableStubDriver : StubDriver, IWritable`, `SubscribableStubDriver : StubDriver, ISubscribable`, and nested `StubHandle : ISubscriptionHandle`. `DriverInstanceActorTests`' copy is a **superset** (adds `ReinitializeCount`, `InitConfigs`, `InitBehavior`, `UnsubscribeYields`, `LastSubscribedRefs`). The de-dup should promote the **superset** versions to shared `internal` classes so both suites compile, then delete both private copies.
**Steps:**
1. Read both test files' stub regions to capture the exact superset (the `DriverInstanceActorTests` versions).
2. Create `StubDrivers.cs` with `internal` `StubDriver`, `WritableStubDriver`, `SubscribableStubDriver`, `StubHandle` = the superset versions (keep all the doc-comments so doc-checker stays clean). Use the same namespace as the two test files.
3. Delete the private nested copies from both `DriverInstanceActorTests.cs` and `DriverInstanceActorWriteAndSubscribeTests.cs`.
4. Run the WHOLE project (both suites share the harness): `dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests` — expect green, same test count as before.
5. Commit `test(drivers): extract shared stub-driver harness (de-dup)`.
**Acceptance:** both suites compile + pass against the single shared harness; no test removed; no production file touched.
---
### Task 5: Reconcile pending.md (disk-only, NOT committed)
**Classification:** trivial — performed by the controller, not a subagent.
Update `pending.md` open-item #3 to record the verified already-done follow-ups (with file:line evidence) and mark the four items above closed. `pending.md` is a disk-only working-notes file and is **not staged/committed** (standing hard rule), so this is a working-tree edit only.
@@ -0,0 +1,11 @@
{
"planPath": "docs/plans/2026-06-14-residual-followups-cleanup-plan.md",
"tasks": [
{"id": 1, "subject": "Task 1: Phase B (a) regression test — native alarm during Reconnecting is dropped", "status": "pending"},
{"id": 2, "subject": "Task 2: Phase B (b) test — OperatorComment flows through ForwardNativeAlarm", "status": "pending"},
{"id": 3, "subject": "Task 3: Phase B (c) doc note — severity-bucket snapping (ScriptedAlarms.md)", "status": "pending"},
{"id": 4, "subject": "Task 4: Galaxy (3) — extract shared stub-driver test harness (de-dup)", "status": "pending"},
{"id": 5, "subject": "Task 5: Reconcile pending.md (disk-only, not committed)", "status": "pending"}
],
"lastUpdated": "2026-06-14"
}
@@ -188,6 +188,44 @@ public sealed class DriverHostActorNativeAlarmTests : RuntimeActorTestBase
alerts.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
/// <summary>A native alarm whose <c>AlarmEventArgs.OperatorComment</c> is set flows through
/// <c>DriverHostActor.ForwardNativeAlarm</c> into the published <see cref="AlarmTransitionEvent"/>:
/// <c>Comment</c> carries the operator string and <c>User</c> is <c>"device"</c> (a non-null comment
/// signals the upstream alarm system provided an operator origin, but without a specific user identity).
/// </summary>
[Fact]
public void Native_alarm_operator_comment_flows_to_transition_event()
{
var db = NewInMemoryDbFactory();
var deploymentId = SeedDeploymentWithAlarmTag(db, RevA,
Equip: "eq-1", Driver: "drv-1", FullName: "Temp.HiHi", Folder: null, Name: "temp_hi");
var alerts = CreateTestProbe();
SubscribeToAlerts(alerts);
var (actor, publish) = SpawnHostAndApply(db, deploymentId);
// Send an alarm whose OperatorComment is set — simulates an upstream acknowledge-with-comment.
actor.Tell(new DriverInstanceActor.AttributeAlarmPublished("drv-1", new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "Temp",
ConditionId: "Temp.HiHi",
AlarmType: "OffNormalAlarm",
Message: "investigating",
Severity: AlarmSeverity.High,
SourceTimestampUtc: Ts,
Kind: AlarmTransitionKind.Acknowledge,
OperatorComment: "investigating")));
// OPC UA condition update is ungated — drain it.
publish.ExpectMsg<OpcUaPublishActor.AlarmStateUpdate>(TimeSpan.FromSeconds(5));
// The published AlarmTransitionEvent must carry the comment + the "device" user marker.
var evt = alerts.ExpectMsg<AlarmTransitionEvent>(TimeSpan.FromSeconds(5));
evt.Comment.ShouldBe("investigating");
evt.User.ShouldBe("device");
}
/// <summary>Subscribe <paramref name="probe"/> to the <c>alerts</c> DPS topic and wait for the ack.
/// The Subscribe is sent FROM the probe so the SubscribeAck returns to it. Mirrors the
/// ScriptedAlarmHostActor test harness.</summary>
@@ -1,4 +1,5 @@
using Akka.Actor;
using Akka.Event;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
@@ -91,6 +92,84 @@ public sealed class DriverInstanceActorNativeAlarmTests : RuntimeActorTestBase
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
}
/// <summary>
/// A native alarm transition that races in while the actor is in <c>Reconnecting</c> is silently
/// dropped (debug log only) — it NEVER reaches the parent as
/// <see cref="DriverInstanceActor.AttributeAlarmPublished"/> AND is NOT dead-lettered (the
/// <c>Reconnecting</c> state's explicit <c>Receive&lt;NativeAlarmRaised&gt;</c> handler consumes and
/// discards it, so it never becomes unhandled). The feed re-delivers active alarms once the actor
/// re-enters <c>Connected</c>, so dropping here is safe.
/// (<see cref="DriverInstanceActor"/> line ~345: the <c>Reconnecting</c> state's
/// <c>Receive&lt;NativeAlarmRaised&gt;</c> logs a debug message and discards.)
///
/// <para>
/// To reproduce the race deterministically: a <c>ForceReconnect</c> is enqueued first, then
/// the driver fires an alarm while its <c>OnAlarmEvent</c> handler is still attached (the actor
/// hasn't yet processed <c>ForceReconnect</c>). The handler's <c>self.Tell(NativeAlarmRaised)</c>
/// lands second in the mailbox. The actor then processes <c>ForceReconnect</c> → Reconnecting
/// (detaches handler), then processes the queued <c>NativeAlarmRaised</c> in Reconnecting
/// → drops it. The default 10 s reconnect interval ensures no retry fires during the check.
/// </para>
///
/// <para>
/// Both properties are actively asserted: (a) the parent probe receives no
/// <see cref="DriverInstanceActor.AttributeAlarmPublished"/>; (b) a dead-letter probe subscribed
/// to <see cref="AllDeadLetters"/> on the <see cref="ActorSystem.EventStream"/> also receives
/// nothing — proving the drop handler is present (removing it would cause a dead-letter and fail
/// this assertion). <c>NativeAlarmRaised</c> is private to the actor, so the dead-letter probe
/// subscribes to the unfiltered <see cref="AllDeadLetters"/> channel; this is safe because
/// exactly one message is injected and the reconnect timer (10 s) cannot fire in the window.
/// </para>
/// </summary>
[Fact]
public void Native_alarm_during_reconnect_is_dropped_not_forwarded()
{
// Subscribe a dead-letter probe BEFORE injecting the alarm so we don't miss any early publish.
// NativeAlarmRaised is private, so we subscribe to the unfiltered AllDeadLetters channel.
// Only one message is injected and the 10 s reconnect timer can't fire in this window, so
// a plain "no dead letters at all" assertion is safe and non-flaky.
var deadLetters = CreateTestProbe();
Sys.EventStream.Subscribe(deadLetters.Ref, typeof(AllDeadLetters));
// Long reconnect interval (default 10 s) so the retry doesn't fire during the assertion window.
var driver = new AlarmSourceStubDriver();
var parent = CreateTestProbe();
var actor = parent.ChildActorOf(DriverInstanceActor.Props(driver));
// Drive to Connected; confirm the alarm handler is attached.
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
AwaitCondition(() => driver.AlarmSubscriberCount == 1, TimeSpan.FromSeconds(2));
// Enqueue ForceReconnect FIRST — the actor hasn't processed it yet, so the handler is
// still wired. The test thread then immediately fires the alarm on the driver; the handler's
// self.Tell(NativeAlarmRaised) lands SECOND in the mailbox.
actor.Tell(new DriverInstanceActor.ForceReconnect());
driver.RaiseAlarm(new AlarmEventArgs(
new StubAlarmHandle(),
SourceNodeId: "src-node-reconnect",
ConditionId: "cond-reconnect",
AlarmType: "T",
Message: "during-reconnect raise",
Severity: AlarmSeverity.High,
SourceTimestampUtc: DateTime.UtcNow,
Kind: AlarmTransitionKind.Raise));
// (a) The parent must NOT receive AttributeAlarmPublished from that alarm.
// The actor processes: (1) ForceReconnect → Reconnecting (handler detached);
// (2) NativeAlarmRaised → dropped (debug log, no forward).
// Wait generously — the default reconnect interval of 10 s means no retry fires here.
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
// (b) The alarm must also NOT have dead-lettered — the Reconnecting state's explicit
// Receive<NativeAlarmRaised> handler must have consumed it. If that handler were removed the
// message would become unhandled → AllDeadLetters, and this assertion would catch the regression.
deadLetters.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
// The actor must still be alive — Watch + no Terminated.
Watch(actor);
parent.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
}
/// <summary>
/// After a full reconnect cycle (Connected → Reconnecting → Connected), a single raised alarm still
/// yields EXACTLY ONE <see cref="DriverInstanceActor.AttributeAlarmPublished"/> — the
@@ -322,142 +322,4 @@ public sealed class DriverInstanceActorTests : RuntimeActorTestBase
AwaitCondition(() => driver.SubscribeCount >= 1, TimeSpan.FromSeconds(3));
}
private class StubDriver : IDriver
{
/// <summary>Gets or sets a value indicating whether initialization should throw.</summary>
public bool InitializeShouldThrow { get; set; }
/// <summary>Gets the number of times initialization was called.</summary>
public int InitializeCount;
/// <summary>Gets the number of times reinitialization was called.</summary>
public int ReinitializeCount;
private readonly object _initConfigsLock = new();
/// <summary>Every config string passed to <see cref="InitializeAsync"/>, in call order.</summary>
public List<string> InitConfigs { get; } = new();
/// <summary>Optional per-config init behaviour. When set, it fully owns the init outcome for that
/// config (await/throw); <see cref="InitializeShouldThrow"/> is ignored. Null ⇒ legacy behaviour.</summary>
public Func<string, Task>? InitBehavior { get; set; }
/// <summary>Gets the driver instance ID.</summary>
public string DriverInstanceId => "stub-driver-1";
/// <summary>Gets the driver type.</summary>
public string DriverType => "Stub";
/// <summary>Initializes the driver with the specified configuration JSON.</summary>
/// <param name="driverConfigJson">The driver configuration JSON.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref InitializeCount);
lock (_initConfigsLock) InitConfigs.Add(driverConfigJson);
if (InitBehavior is not null) { await InitBehavior(driverConfigJson); return; }
if (InitializeShouldThrow) throw new InvalidOperationException("stub-init-fail");
}
/// <summary>Reinitializes the driver with the specified configuration JSON.</summary>
/// <param name="driverConfigJson">The driver configuration JSON.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref ReinitializeCount);
return Task.CompletedTask;
}
/// <summary>Shuts down the driver.</summary>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>Gets the health status of the driver.</summary>
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
/// <summary>Gets the memory footprint of the driver.</summary>
public long GetMemoryFootprint() => 0;
/// <summary>Flushes optional caches in the driver.</summary>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task FlushOptionalCachesAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
private sealed class WritableStubDriver : StubDriver, IWritable
{
/// <summary>Gets or sets the next status code to return from write operations.</summary>
public uint NextStatusCode { get; set; } = 0u;
/// <summary>Gets the list of write requests received.</summary>
public List<WriteRequest> Writes { get; } = new();
/// <summary>Writes the specified requests.</summary>
/// <param name="writes">The write requests.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
Writes.AddRange(writes);
IReadOnlyList<WriteResult> results = writes.Select(_ => new WriteResult(NextStatusCode)).ToList();
return Task.FromResult(results);
}
}
private sealed class SubscribableStubDriver : StubDriver, ISubscribable
{
/// <summary>Occurs when data changes.</summary>
public event EventHandler<DataChangeEventArgs>? OnDataChange;
private readonly StubHandle _handle = new();
/// <summary>Gets the number of subscribers to OnDataChange.</summary>
public int OnDataChangeSubscriberCount => OnDataChange?.GetInvocationList().Length ?? 0;
/// <summary>Number of times <see cref="SubscribeAsync"/> was called (re-subscribe asserts).</summary>
public int SubscribeCount;
/// <summary>The reference set passed to the most recent <see cref="SubscribeAsync"/> call.</summary>
public IReadOnlyList<string>? LastSubscribedRefs;
/// <summary>When true, <see cref="UnsubscribeAsync"/> genuinely yields (`await Task.Yield()`)
/// before completing, so a `ConfigureAwait(false)` continuation in the actor resumes off the
/// Akka ActorContext on a thread-pool thread — reproducing the no-ActorContext race that a
/// synchronously-completed stub task hides (the continuation otherwise runs inline).</summary>
public bool UnsubscribeYields { get; set; }
/// <summary>Subscribes to the specified full references.</summary>
/// <param name="fullReferences">The full references to subscribe to.</param>
/// <param name="publishingInterval">The publishing interval.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
Interlocked.Increment(ref SubscribeCount);
LastSubscribedRefs = fullReferences;
return Task.FromResult<ISubscriptionHandle>(_handle);
}
/// <summary>Unsubscribes from the specified subscription handle.</summary>
/// <param name="handle">The subscription handle.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
{
if (UnsubscribeYields)
{
// Complete the awaited task from a fresh background thread that has NO Akka actor
// cell on it, so the caller's `ConfigureAwait(false)` continuation resumes on a
// clean thread-pool thread where InternalCurrentActorCellKeeper.Current is null —
// a deterministic repro of the real async-backend no-ActorContext race.
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_ = Task.Run(() => tcs.SetResult());
await tcs.Task.ConfigureAwait(false);
}
}
/// <summary>Fires a data change event with the specified parameters.</summary>
/// <param name="fullRef">The full reference of the data that changed.</param>
/// <param name="value">The new value.</param>
/// <param name="statusCode">The OPC UA status code.</param>
public void FireDataChange(string fullRef, object? value, uint statusCode)
{
var snapshot = new DataValueSnapshot(value, statusCode, DateTime.UtcNow, DateTime.UtcNow);
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullRef, snapshot));
}
private sealed class StubHandle : ISubscriptionHandle
{
/// <summary>Gets the diagnostic ID of the subscription.</summary>
public string DiagnosticId => "stub-sub";
}
}
}
@@ -173,42 +173,6 @@ public sealed class DriverInstanceActorWriteAndSubscribeTests : RuntimeActorTest
deadLetterProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
// --- stub drivers (mirrors DriverInstanceActorTests) ------------------------------------------
private class StubDriver : IDriver
{
/// <summary>Gets or sets a value indicating whether initialization should throw.</summary>
public bool InitializeShouldThrow { get; set; }
/// <summary>Gets the number of times initialization was called.</summary>
public int InitializeCount;
/// <summary>Gets the driver instance ID.</summary>
public string DriverInstanceId => "stub-driver-1";
/// <summary>Gets the driver type.</summary>
public string DriverType => "Stub";
/// <summary>Initializes the driver with the specified configuration JSON.</summary>
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref InitializeCount);
if (InitializeShouldThrow) throw new InvalidOperationException("stub-init-fail");
return Task.CompletedTask;
}
/// <summary>Reinitializes the driver with the specified configuration JSON.</summary>
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Shuts down the driver.</summary>
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>Gets the health status of the driver.</summary>
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
/// <summary>Gets the memory footprint of the driver.</summary>
public long GetMemoryFootprint() => 0;
/// <summary>Flushes optional caches in the driver.</summary>
public Task FlushOptionalCachesAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
/// <summary>
/// A standalone <see cref="IDriver"/> (and <see cref="IWritable"/>) whose <c>InitializeAsync</c>
/// never completes, parking the actor in <c>Connecting</c>. Implements the interface directly
@@ -255,59 +219,4 @@ public sealed class DriverInstanceActorWriteAndSubscribeTests : RuntimeActorTest
}
}
private sealed class WritableStubDriver : StubDriver, IWritable
{
/// <summary>Gets or sets the next status code to return from write operations.</summary>
public uint NextStatusCode { get; set; } = 0u;
/// <summary>Gets the list of write requests received.</summary>
public List<WriteRequest> Writes { get; } = new();
/// <summary>Writes the specified requests.</summary>
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
Writes.AddRange(writes);
IReadOnlyList<WriteResult> results = writes.Select(_ => new WriteResult(NextStatusCode)).ToList();
return Task.FromResult(results);
}
}
private sealed class SubscribableStubDriver : StubDriver, ISubscribable
{
/// <summary>Occurs when data changes.</summary>
public event EventHandler<DataChangeEventArgs>? OnDataChange;
private readonly StubHandle _handle = new();
/// <summary>Gets the number of subscribers to OnDataChange.</summary>
public int OnDataChangeSubscriberCount => OnDataChange?.GetInvocationList().Length ?? 0;
/// <summary>Number of times <see cref="SubscribeAsync"/> was called.</summary>
public int SubscribeCount;
/// <summary>Subscribes to the specified full references.</summary>
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
Interlocked.Increment(ref SubscribeCount);
return Task.FromResult<ISubscriptionHandle>(_handle);
}
/// <summary>Unsubscribes from the specified subscription handle.</summary>
public Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken) =>
Task.CompletedTask;
/// <summary>Fires a data change event with the specified parameters.</summary>
public void FireDataChange(string fullRef, object? value, uint statusCode)
{
var snapshot = new DataValueSnapshot(value, statusCode, DateTime.UtcNow, DateTime.UtcNow);
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullRef, snapshot));
}
private sealed class StubHandle : ISubscriptionHandle
{
/// <summary>Gets the diagnostic ID of the subscription.</summary>
public string DiagnosticId => "stub-sub";
}
}
}
@@ -0,0 +1,158 @@
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Shared <see cref="IDriver"/> stub harness used by <c>DriverInstanceActorTests</c> and
/// <c>DriverInstanceActorWriteAndSubscribeTests</c>. Promoted from the superset copy in
/// <c>DriverInstanceActorTests</c> so both suites compile against a single definition.
/// </summary>
internal class StubDriver : IDriver
{
/// <summary>Gets or sets a value indicating whether initialization should throw.</summary>
public bool InitializeShouldThrow { get; set; }
/// <summary>Gets the number of times initialization was called.</summary>
public int InitializeCount;
/// <summary>Gets the number of times reinitialization was called.</summary>
public int ReinitializeCount;
private readonly object _initConfigsLock = new();
/// <summary>Every config string passed to <see cref="InitializeAsync"/>, in call order.</summary>
public List<string> InitConfigs { get; } = new();
/// <summary>Optional per-config init behaviour. When set, it fully owns the init outcome for that
/// config (await/throw); <see cref="InitializeShouldThrow"/> is ignored. Null ⇒ legacy behaviour.</summary>
public Func<string, Task>? InitBehavior { get; set; }
/// <summary>Gets the driver instance ID.</summary>
public string DriverInstanceId => "stub-driver-1";
/// <summary>Gets the driver type.</summary>
public string DriverType => "Stub";
/// <summary>Initializes the driver with the specified configuration JSON.</summary>
/// <param name="driverConfigJson">The driver configuration JSON.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref InitializeCount);
lock (_initConfigsLock) InitConfigs.Add(driverConfigJson);
if (InitBehavior is not null) { await InitBehavior(driverConfigJson); return; }
if (InitializeShouldThrow) throw new InvalidOperationException("stub-init-fail");
}
/// <summary>Reinitializes the driver with the specified configuration JSON.</summary>
/// <param name="driverConfigJson">The driver configuration JSON.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task ReinitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
Interlocked.Increment(ref ReinitializeCount);
return Task.CompletedTask;
}
/// <summary>Shuts down the driver.</summary>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task ShutdownAsync(CancellationToken cancellationToken) => Task.CompletedTask;
/// <summary>Gets the health status of the driver.</summary>
public DriverHealth GetHealth() => new(DriverState.Healthy, DateTime.UtcNow, null);
/// <summary>Gets the memory footprint of the driver.</summary>
public long GetMemoryFootprint() => 0;
/// <summary>Flushes optional caches in the driver.</summary>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task FlushOptionalCachesAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
/// <summary>
/// A <see cref="StubDriver"/> that also implements <see cref="IWritable"/>, recording every
/// write call and returning a configurable status code.
/// </summary>
internal sealed class WritableStubDriver : StubDriver, IWritable
{
/// <summary>Gets or sets the next status code to return from write operations.</summary>
public uint NextStatusCode { get; set; } = 0u;
/// <summary>Gets the list of write requests received.</summary>
public List<WriteRequest> Writes { get; } = new();
/// <summary>Writes the specified requests.</summary>
/// <param name="writes">The write requests.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
Writes.AddRange(writes);
IReadOnlyList<WriteResult> results = writes.Select(_ => new WriteResult(NextStatusCode)).ToList();
return Task.FromResult(results);
}
}
/// <summary>
/// A <see cref="StubDriver"/> that also implements <see cref="ISubscribable"/>, firing
/// <see cref="OnDataChange"/> on demand and counting subscribe calls.
/// </summary>
internal sealed class SubscribableStubDriver : StubDriver, ISubscribable
{
/// <summary>Occurs when data changes.</summary>
public event EventHandler<DataChangeEventArgs>? OnDataChange;
private readonly StubHandle _handle = new();
/// <summary>Gets the number of subscribers to OnDataChange.</summary>
public int OnDataChangeSubscriberCount => OnDataChange?.GetInvocationList().Length ?? 0;
/// <summary>Number of times <see cref="SubscribeAsync"/> was called (re-subscribe asserts).</summary>
public int SubscribeCount;
/// <summary>The reference set passed to the most recent <see cref="SubscribeAsync"/> call.</summary>
public IReadOnlyList<string>? LastSubscribedRefs;
/// <summary>When true, <see cref="UnsubscribeAsync"/> genuinely yields (<c>await Task.Yield()</c>)
/// before completing, so a <c>ConfigureAwait(false)</c> continuation in the actor resumes off the
/// Akka ActorContext on a thread-pool thread — reproducing the no-ActorContext race that a
/// synchronously-completed stub task hides (the continuation otherwise runs inline).</summary>
public bool UnsubscribeYields { get; set; }
/// <summary>Subscribes to the specified full references.</summary>
/// <param name="fullReferences">The full references to subscribe to.</param>
/// <param name="publishingInterval">The publishing interval.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
Interlocked.Increment(ref SubscribeCount);
LastSubscribedRefs = fullReferences;
return Task.FromResult<ISubscriptionHandle>(_handle);
}
/// <summary>Unsubscribes from the specified subscription handle.</summary>
/// <param name="handle">The subscription handle.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
public async Task UnsubscribeAsync(ISubscriptionHandle handle, CancellationToken cancellationToken)
{
if (UnsubscribeYields)
{
// Complete the awaited task from a fresh background thread that has NO Akka actor
// cell on it, so the caller's `ConfigureAwait(false)` continuation resumes on a
// clean thread-pool thread where InternalCurrentActorCellKeeper.Current is null —
// a deterministic repro of the real async-backend no-ActorContext race.
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_ = Task.Run(() => tcs.SetResult());
await tcs.Task.ConfigureAwait(false);
}
}
/// <summary>Fires a data change event with the specified parameters.</summary>
/// <param name="fullRef">The full reference of the data that changed.</param>
/// <param name="value">The new value.</param>
/// <param name="statusCode">The OPC UA status code.</param>
public void FireDataChange(string fullRef, object? value, uint statusCode)
{
var snapshot = new DataValueSnapshot(value, statusCode, DateTime.UtcNow, DateTime.UtcNow);
OnDataChange?.Invoke(this, new DataChangeEventArgs(_handle, fullRef, snapshot));
}
}
/// <summary>Minimal <see cref="ISubscriptionHandle"/> for use by <see cref="SubscribableStubDriver"/>.</summary>
internal sealed class StubHandle : ISubscriptionHandle
{
/// <summary>Gets the diagnostic ID of the subscription.</summary>
public string DiagnosticId => "stub-sub";
}