Compare commits

...

9 Commits

Author SHA1 Message Date
Joseph Doherty 945c238039 docs(plans): harden-milestone-1b plan + task record
v2-ci / build (push) Failing after 48s
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
2026-06-14 00:51:05 -04:00
Joseph Doherty 190ef34e6f docs(security): document the GroupToRole data-plane role requirement 2026-06-14 00:45:28 -04:00
Joseph Doherty 97d82dda46 test(runtime): future-enum trap for AccessLevel->Writable parity 2026-06-14 00:45:00 -04:00
Joseph Doherty 7e405e949b fix(runtime): swallow self SubscriptionFailed too (symmetric to SubscriptionEstablished) 2026-06-14 00:42:31 -04:00
Joseph Doherty f77488eed9 fix(galaxy): invalidate writer handle caches on session reconnect
Add IGalaxyDataWriter.InvalidateHandleCaches() and call it in
GalaxyDriver.ReopenAsync after RecreateAsync succeeds. Prior to this
fix, GatewayGalaxyDataWriter's _itemHandles and _supervisedHandles
dictionaries survived across reconnects, causing the next write to
skip AddItem and AdviseSupervisory against already-dead handles.
2026-06-14 00:39:24 -04:00
Joseph Doherty 42b4a923fd fix(runtime): fast-fail writes in degraded driver states + swallow self SubscriptionEstablished 2026-06-14 00:34:37 -04:00
Joseph Doherty 99eea0b455 test(runtime): raw-blob routing test uses a no-FullName protocol blob (genuine #4d case) 2026-06-14 00:26:10 -04:00
Joseph Doherty 46f559f5f9 perf(focas): cache equipment-tag parsed addresses (no per-call reparse)
Equipment tags resolved at runtime via FocasEquipmentTagParser were not
seeded in _parsedAddressesByTagName so both ReadAsync and WriteAsync
re-parsed the raw TagConfig JSON address string on every hot-path call.
Promoted the field to ConcurrentDictionary (read + write thread safety)
and introduced ResolveParsedAddress(GetOrAdd) so the first call stores
the parse result and all subsequent calls are a cache hit. Authored tags
seeded at InitializeAsync compile and work unchanged.
2026-06-14 00:20:57 -04:00
Joseph Doherty 4cda275b8d fix(runtime): fast-fail RouteNodeWrite while Stale + micro-opts + raw-blob routing test 2026-06-14 00:16:47 -04:00
17 changed files with 1291 additions and 24 deletions
@@ -0,0 +1,557 @@
# Harden Milestone 1b — Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:executing-plans (or subagent-driven-development) to implement this plan task-by-task.
**Goal:** Close out the review nits left from the just-shipped Milestone 1b (equipment-tag live values + inbound operator-write pipeline) — fast-fail degraded-state writes, two micro-optimisations, a FOCAS equipment-tag parse-cache gap, a benign Galaxy dead-letter, a Galaxy reconnect stale-handle gap, two test-hardening additions, and one deployment-facing docs note.
**Architecture:** Pure hardening — no new feature surface, **no EF/Configuration schema change, no migration**. Changes are additive fast-fail handlers on existing actor behaviours, a thread-safe cache swap, a writer cache-invalidation seam on the Galaxy reconnect path, test additions, and a docs subsection. Source of these items: `pending.md` follow-ups #3, #4, #6 (from the Milestone 1b integration review), all enumerated below.
**Tech Stack:** C# / .NET 10, Akka.NET (DriverHostActor / DriverInstanceActor), xUnit + Shouldly + Akka.TestKit. `TreatWarningsAsErrors` is on solution-wide.
**Branch:** `chore/harden-milestone-1b` off `master` (HEAD `02e37a6d`).
**Hard rules (every task):** stage by path (never `git add .`); never stage `sql_login.txt` / `src/Server/ZB.MOM.WW.OtOpcUa.Host/pki/` / `pending.md` / `current.md` / `docker-dev/docker-compose.yml`; never echo secrets; no force-push / no `--no-verify`; **NO Configuration entity / EF migration change**. Done = build clean + `dotnet test` green for every touched project.
---
## Task DAG
```
T0 (branch)
├─ T1 DriverHostActor: Stale fast-fail + micro-opts + raw-blob routing test [standard]
├─ T2 DriverInstanceActor: Connecting/Reconnecting/Stubbed write fast-fail
│ + benign SubscriptionEstablished handler [standard]
├─ T3 FOCAS: cache equipment-tag parsed addresses (ConcurrentDictionary) [small]
├─ T4 Parity test: future-enum trap InlineData(2,false) [trivial]
├─ T5 docs/security.md: data-plane GroupToRole requirement note [trivial]
└─ T6 Galaxy writer: invalidate handle caches on reconnect [small]
```
T1–T6 all `blockedBy` T0 and have **disjoint file sets** — they are mutually `Parallelizable`. Dispatch them concurrently after T0.
---
### Task T0: Create feature branch
**Classification:** trivial
**Estimated implement time:** ~1 min
**Parallelizable with:** none (gates all)
**Files:** none (git only)
**Step 1: Branch off master**
```bash
git -C /Users/dohertj2/Desktop/OtOpcUa checkout -b chore/harden-milestone-1b master
git -C /Users/dohertj2/Desktop/OtOpcUa rev-parse --abbrev-ref HEAD # expect: chore/harden-milestone-1b
```
Do NOT touch the working-tree `docker-dev/docker-compose.yml` (leave it modified+unstaged throughout).
---
### Task T1: DriverHostActor — Stale-state write fast-fail + micro-opts + raw-blob routing test
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** T2, T3, T4, T5, T6
Addresses pending.md #4(a-host), #4(b), #4(d).
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs` (Stale behaviour ~537-550; `HandleRouteNodeWrite` ContinueWith line 519; forward-map build line 754-756)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorWriteRoutingTests.cs`
**Context:** `RouteNodeWrite`/`NodeWriteResult` are defined at `DriverHostActor.cs:130,136`. The running behaviour wires `HandleRouteNodeWrite`, but the **`Stale()`** behaviour (DB unreachable; lines 537-550) has no `RouteNodeWrite` handler → an inbound operator write while Stale dead-letters and the node-manager's 10 s Ask times out with a generic log (the client already got the optimistic `Good`). Add a fast-fail. Two micro-opts ride along in the same file.
**Step 1: Add the failing Akka.TestKit test for Stale fast-fail**
In `DriverHostActorWriteRoutingTests.cs`, add a test that drives the host into `Stale` (construct it with a DB factory that throws, or send whatever the existing tests use to reach Stale — mirror an existing Stale-path test in the file/suite) and asserts an immediate negative `NodeWriteResult`:
```csharp
[Fact]
public void RouteNodeWrite_while_stale_fast_fails_instead_of_timing_out()
{
// Arrange: a host that cannot reach the config DB enters Stale on first DispatchDeployment.
var host = /* spawn DriverHostActor with a throwing IDbContextFactory — reuse the suite's Stale helper */;
DriveIntoStale(host);
// Act
host.Tell(new DriverHostActor.RouteNodeWrite("ns=2;s=EQ-x/Tag", 42), TestActor);
var reply = ExpectMsg<DriverHostActor.NodeWriteResult>(TimeSpan.FromSeconds(2));
// Assert: fast negative, not a ~10s timeout
reply.Success.ShouldBeFalse();
reply.Reason.ShouldContain("stale");
}
```
If the suite has no existing Stale helper, reach Stale the same way the existing "ignoring DispatchDeployment while Stale" coverage does; if none exists, construct the actor with a `IDbContextFactory` stub whose `CreateDbContext` throws and send the message that triggers the DB read. Keep the helper local to the test file.
**Step 2: Run it — expect FAIL (times out / dead-letters, no reply)**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests \
--filter "FullyQualifiedName~RouteNodeWrite_while_stale_fast_fails"
```
**Step 3: Add the Stale fast-fail handler**
In `DriverHostActor.cs` `Stale()` (after the existing `Receive<RedundancyStateChanged>` line 547), add:
```csharp
// An inbound operator write can't be serviced while the config DB is unreachable — fast-fail so the
// node-manager's bounded Ask gets an immediate clear status instead of dead-lettering into a timeout.
Receive<RouteNodeWrite>(_ =>
Sender.Tell(new NodeWriteResult(false, "driver host stale (config DB unreachable)")));
```
**Step 4: Micro-opt — drop `ExecuteSynchronously` on the router continuation**
In `HandleRouteNodeWrite` (line 514-520), the `.ContinueWith(...)` passes `TaskContinuationOptions.ExecuteSynchronously`. Running the continuation synchronously on the Ask's completing thread (a pool/transport thread) is needless coupling for a tiny projection. Change it to `TaskContinuationOptions.None`:
```csharp
.ContinueWith(
t => t.IsCompletedSuccessfully
? new NodeWriteResult(t.Result.Success, t.Result.Reason)
: new NodeWriteResult(false, "write timeout"),
CancellationToken.None,
TaskContinuationOptions.None,
TaskScheduler.Default)
.PipeTo(replyTo);
```
**Step 5: Micro-opt — `List.Contains` → `HashSet` in the forward-map build**
The forward map `_nodeIdByDriverRef` (declared as `Dictionary<.., List<string>>`) does `if (!list.Contains(nodeId)) list.Add(nodeId);` at line 756 — O(n) per node. Convert the value type to `HashSet<string>`:
- Change the field declaration to `Dictionary<(string,string), HashSet<string>>` (keep `StringComparer.Ordinal` on the inner set).
- Line 754-756 becomes:
```csharp
if (!_nodeIdByDriverRef.TryGetValue(key, out var set))
_nodeIdByDriverRef[key] = set = new HashSet<string>(StringComparer.Ordinal);
set.Add(nodeId);
```
- **Grep every consumer of `_nodeIdByDriverRef`** (`grep -n _nodeIdByDriverRef src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs`) and confirm they only `foreach`/`Count`/membership-check the value (all of which `HashSet` supports). If any consumer indexes by position (`list[i]`) leave it a `List` and skip this micro-opt — note that in the commit message. (Expected: ForwardToMux only enumerates.)
**Step 6: Raw protocol-blob routing test (#4d)**
The suite seeds equipment tags with `TagConfig = JsonSerializer.Serialize(new { FullName = t.FullName })` (a Galaxy-style `{FullName}` blob). The router keys purely on **NodeId**, so the TagConfig blob shape is irrelevant to routing — prove that with a raw protocol blob. Add a tag to the seeded composition (or a new focused test) whose `TagConfig` is a raw Modbus-style blob and assert the write still routes to the owning driver by NodeId:
```csharp
[Fact]
public void RouteNodeWrite_routes_by_nodeId_regardless_of_raw_tagconfig_blob_shape()
{
// Seed an equipment tag whose TagConfig is a RAW protocol blob (region/address), NOT {FullName}.
var rawBlob = JsonSerializer.Serialize(new { region = "HoldingRegister", address = 200, dataType = "UInt16" });
var host = SeedHostWithEquipmentTag(driverId: "MAIN-modbus-eq", tagConfig: rawBlob, /* nodeId derived as in the suite */);
host.Tell(new DriverHostActor.RouteNodeWrite(expectedNodeId, (ushort)7), TestActor);
// The child receives WriteAttribute carrying the wire-ref FullName (the blob is the wire-ref here);
// assert via the suite's existing child probe that the write was forwarded (Success path).
var reply = ExpectMsg<DriverHostActor.NodeWriteResult>();
reply.Success.ShouldBeTrue();
}
```
Reuse the suite's existing child-probe / seed helpers (the file already exercises `RouteNodeWrite` happy-path — clone that setup and only swap the `TagConfig` to the raw blob). The point is belt-and-suspenders: routing is blob-shape-independent.
**Step 7: Run the full routing suite — expect PASS**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DriverHostActorWriteRouting"
```
**Step 8: Build + commit (stage by path)**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverHostActor.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverHostActorWriteRoutingTests.cs
git commit -m "fix(runtime): fast-fail RouteNodeWrite while Stale + micro-opts + raw-blob routing test"
```
---
### Task T2: DriverInstanceActor — write fast-fail in degraded states + benign SubscriptionEstablished handler
**Classification:** standard
**Estimated implement time:** ~5 min
**Parallelizable with:** T1, T3, T4, T5, T6
Addresses pending.md #4(a-instance) and #6(a).
**Files:**
- Modify: `src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs` (Stubbed ~205-209; `Connecting()` 211-231; `Reconnecting()` 265-281; `Connected()` 233-263)
- Test: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorWriteAndSubscribeTests.cs` (NEW file — avoids touching T1's test file)
**Context:**
- `WriteAttribute`/`WriteAttributeResult` are at lines 41-42. Only `Connected()` handles `WriteAttribute` (line 252). When the actor is `Connecting`/`Reconnecting`/`Stubbed`, an inbound `WriteAttribute` (Asked by `DriverHostActor.HandleRouteNodeWrite` with an 8 s timeout) dead-letters → the Ask times out as a generic "write timeout". Fast-fail in those states with a clear reason.
- `ResubscribeDesired()` (line 437-443) does `Self.Tell(new Subscribe(...))`; `HandleSubscribeAsync` replies `SubscriptionEstablished` to `replyTo = Sender = Self` (line 379) → no handler → the benign dead-letter `Message [SubscriptionEstablished] from drv-… to drv-… was unhandled` seen live on Galaxy. This is the **generic** actor, so a no-op handler quiets it for every driver.
**Step 1: Failing tests (new file)**
```csharp
public sealed class DriverInstanceActorWriteAndSubscribeTests : TestKit
{
[Fact]
public void WriteAttribute_while_connecting_fast_fails()
{
var actor = SpawnInConnectingState(); // see helper note below
actor.Tell(new DriverInstanceActor.WriteAttribute("Tag.Attr", 1), TestActor);
var r = ExpectMsg<DriverInstanceActor.WriteAttributeResult>(TimeSpan.FromSeconds(2));
r.Success.ShouldBeFalse();
r.Reason.ShouldNotBeNull();
}
[Fact]
public void SubscriptionEstablished_is_swallowed_without_deadletter()
{
var actor = SpawnConnected();
// subscribe with a desired set so ResubscribeDesired self-Tells Subscribe and the reply lands on Self
// Subscribe to DeadLetters and assert none of type SubscriptionEstablished arrive.
var deadLetters = CreateTestProbe();
Sys.EventStream.Subscribe(deadLetters, typeof(DeadLetter));
// drive a (re)subscribe ... then:
deadLetters.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
}
```
Helper note: reuse the spawn/connect helpers the existing DriverInstanceActor tests use (look for them in the Runtime.Tests `Drivers/` folder; there is established setup for stub drivers and the Connected/Reconnecting transitions). To reach `Connecting`, send `InitializeRequested` with a driver-config that the stub keeps pending, or `Become`-drive via the suite's existing harness. If reaching exact internal states is awkward, the **minimum viable** assertions are: (a) a `WriteAttribute` to a Stubbed actor returns a negative `WriteAttributeResult` quickly, and (b) no `SubscriptionEstablished` dead-letter is produced during a connect+resubscribe cycle.
**Step 2: Run — expect FAIL**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DriverInstanceActorWriteAndSubscribe"
```
**Step 3: Add write fast-fail to the three degraded behaviours**
Add this line to `Stubbed` (after line 208), `Connecting()` (after line 230), and `Reconnecting()` (after line 279):
```csharp
Receive<WriteAttribute>(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
```
(Stubbed may use a reason like `"driver stubbed"` — implementer's call; the host maps either into a `NodeWriteResult(false, …)`.)
**Step 4: Add the benign SubscriptionEstablished handler**
In `Connected()` (alongside the other `Receive`s, e.g. after line 262) add a swallow-with-trace so the self-reply from `ResubscribeDesired` doesn't dead-letter:
```csharp
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive<SubscriptionEstablished>(msg =>
_log.Debug("DriverInstance {Id}: subscription established ({Count} refs, {Diag})",
_driverInstanceId, msg.ReferenceCount, msg.DiagnosticId));
```
Add the same one-liner to `Reconnecting()` and `Connecting()` to cover the race where the async subscribe reply lands after a state flip (cheap, same file). Do NOT alter where/how `SubscriptionEstablished` is *sent* — a host that genuinely Asks `Subscribe` still receives its reply (the handler only runs when the message arrives at this actor as the asker).
**Step 5: Run — expect PASS, then build the project**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DriverInstanceActorWriteAndSubscribe"
dotnet build src/Server/ZB.MOM.WW.OtOpcUa.Runtime/ZB.MOM.WW.OtOpcUa.Runtime.csproj
```
**Step 6: Commit (stage by path)**
```bash
git add src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs \
tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DriverInstanceActorWriteAndSubscribeTests.cs
git commit -m "fix(runtime): fast-fail writes in degraded driver states + swallow self SubscriptionEstablished"
```
---
### Task T3: FOCAS — cache equipment-tag parsed addresses
**Classification:** small
**Estimated implement time:** ~4 min
**Parallelizable with:** T1, T2, T4, T5, T6
Addresses pending.md #4(c).
**Files:**
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/FocasDriver.cs` (cache field 37-38; read path 275-280; write path 337-342; init seed 120)
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/` (add to an existing FocasDriver read/write test class)
**Context:** `_parsedAddressesByTagName` (a plain `Dictionary`, line 37) is seeded only from `_options.Tags` at init (line 120). Equipment tags arrive via `_resolver` (line 66) as transient defs whose `Name` is the raw ref — never seeded — so both `ReadAsync` (275-280) and `WriteAsync` (337-342) hit the `TryGetValue` miss and **re-parse `FocasAddress.TryParse(def.Address)` every call without storing**. Fix: make the cache a `ConcurrentDictionary` (reads run on the poll loop, writes on the host Ask thread — concurrent access) and `GetOrAdd` so a transient def's address is parsed once.
**Step 1: Failing test — second resolve must reuse the cache**
Add an `internal` test seam to `FocasDriver` so the test can observe caching without a parser spy:
```csharp
// In FocasDriver (internal, for tests via InternalsVisibleTo — confirm the attribute exists for the .Tests asm)
internal bool IsParsedAddressCached(string reference) => _parsedAddressesByTagName.ContainsKey(reference);
```
Test (equipment-tag ref, not an authored tag):
```csharp
[Fact]
public async Task Equipment_tag_address_is_parsed_once_and_cached()
{
var driver = /* construct FocasDriver with a fake client + one device, no authored Tags */;
await driver.InitializeAsync(configJson, default);
var equipRef = "{\"address\":\"R100\",\"dataType\":\"Int16\",\"deviceHostAddress\":\"focas://10.0.0.5\",\"writable\":true}"; // matches FocasEquipmentTagParser keys
driver.IsParsedAddressCached(equipRef).ShouldBeFalse(); // not seeded at init
await driver.ReadAsync(new[] { equipRef }, default); // first resolve parses + caches
driver.IsParsedAddressCached(equipRef).ShouldBeTrue(); // cached for subsequent hot calls
}
```
Use the exact equipment-ref JSON shape that `FocasEquipmentTagParser.TryParse` accepts (open that parser to copy its camelCase keys + required fields). If `InternalsVisibleTo` for the `.Tests` assembly isn't already present on the FOCAS driver project, add it (mirror how the other drivers expose internals to their test projects).
**Step 2: Run — expect FAIL (second assert false: never cached)**
```bash
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests --filter "FullyQualifiedName~Equipment_tag_address_is_parsed_once"
```
**Step 3: Implement the cache**
- Change the field (line 37-38) to:
```csharp
private readonly ConcurrentDictionary<string, FocasAddress> _parsedAddressesByTagName =
new(StringComparer.OrdinalIgnoreCase);
```
(add `using System.Collections.Concurrent;` if absent).
- Add a private helper:
```csharp
private FocasAddress ResolveParsedAddress(FocasTagDefinition def) =>
_parsedAddressesByTagName.GetOrAdd(def.Name, _ =>
FocasAddress.TryParse(def.Address)
?? throw new InvalidOperationException(
$"FOCAS tag '{def.Name}' has malformed Address '{def.Address}'."));
```
(The throwing factory propagates and does **not** cache a bad parse — preserving the existing fail behaviour. `GetOrAdd` may invoke the factory more than once under race but only stores one — fine, parsing is pure.)
- Replace the read-path block (275-280) and the write-path block (337-342) with `var parsed = ResolveParsedAddress(def);`.
- Line 120 (`_parsedAddressesByTagName[tag.Name] = parsed;`) compiles unchanged on `ConcurrentDictionary`; keep it (init pre-validates + seeds authored tags).
**Step 4: Run — expect PASS, build the project**
```bash
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests --filter "FullyQualifiedName~Equipment_tag_address_is_parsed_once"
dotnet build src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.csproj
```
**Step 5: Commit (stage by path)**
```bash
git add src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS/ tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests/
git commit -m "perf(focas): cache equipment-tag parsed addresses (no per-call reparse)"
```
---
### Task T4: Parity test — future-enum trap
**Classification:** trivial
**Estimated implement time:** ~2 min
**Parallelizable with:** T1, T2, T3, T5, T6
Addresses pending.md #4(e).
**Files:**
- Test only: `tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactAliasParityTests.cs` (numeric-AccessLevel theory ~73-104)
**Context:** `TagAccessLevel` has `Read = 0`, `ReadWrite = 1` (`src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Enums/TagAccessLevel.cs`). The parity test maps numeric AccessLevel → `Writable` with `[InlineData(1, true)]`/`[InlineData(0, false)]`. Add a future-enum guard so an as-yet-undefined value maps fail-safe to non-writable (only `ReadWrite==1` should yield a writable node).
**Step 1: Add the InlineData row**
In the numeric-AccessLevel `[Theory]` (the one with `[InlineData(1, true)]` / `[InlineData(0, false)]`), add:
```csharp
[InlineData(2, false)] // future/unknown AccessLevel must map fail-safe to read-only (only ReadWrite⇒writable)
```
**Step 2: Run — expect PASS (confirms the derivation is `== ReadWrite`, not `!= Read`)**
```bash
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests --filter "FullyQualifiedName~DeploymentArtifactAliasParity"
```
If it FAILS, the production derivation is using `!= Read` (so `2` wrongly maps to writable) — that is a real fail-safety bug; STOP and surface it (the fix would be a one-line `== TagAccessLevel.ReadWrite` in both Phase7Composer and DeploymentArtifact, but only with reviewer sign-off since it touches the byte-parity contract).
**Step 3: Commit (stage by path)**
```bash
git add tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/Drivers/DeploymentArtifactAliasParityTests.cs
git commit -m "test(runtime): future-enum trap for AccessLevel→Writable parity"
```
---
### Task T5: docs/security.md — data-plane GroupToRole requirement
**Classification:** trivial
**Estimated implement time:** ~3 min
**Parallelizable with:** T1, T2, T3, T4, T6
Addresses pending.md #3.
**Files:**
- Modify: `docs/security.md` (Data-Plane Authorization section starts line 167; `GroupToRole` is described at line 163 in the LDAP section; troubleshooting at 313-315)
**Context:** OPC UA session roles are unioned from two sources: the DB `LdapGroupRoleMapping` (whose `Role` column is the **`AdminRole`** enum — Administrator/Designer/Viewer only) AND the appsettings `Security:Ldap:GroupToRole` (free-form `string→string`). The data-plane gates (`WriteOperate`, `WriteTune`, `WriteConfigure`, `AlarmAck`/`AlarmAcknowledge`, `ReadOnly`) read literal **role strings** that the AdminRole-typed DB mapping **cannot produce** — so a deployment MUST map its data-plane LDAP groups → data-plane role strings via `GroupToRole`, or write-through and OPC UA alarm-ack are silently inert (every write → `BadUserAccessDenied`, default-deny). Line 163 currently frames `GroupToRole` as mapping only to *Admin* roles — that's the misleading bit to correct.
**Step 1: Add a "Role grant source (data-plane)" subsection**
Under **## Data-Plane Authorization** (after the "Full model" subsection ~line 241, or right after the "Permission flags" mapping ~216), add a subsection. Suggested content (match the doc's voice; keep it tight):
```markdown
### Role grant source (data-plane)
Data-plane roles come from `Security:Ldap:GroupToRole` (appsettings), **not** from the Config-DB
`LdapGroupRoleMapping` table. That table's `Role` column is the `AdminRole` enum
(`Administrator`/`Designer`/`Viewer`) and supplies **control-plane** roles only — it cannot emit the
data-plane role strings the OPC UA gates read (`ReadOnly`, `WriteOperate`, `WriteTune`,
`WriteConfigure`, `AlarmAcknowledge`). A deployment therefore **must** map its data-plane LDAP groups
to those role strings via `GroupToRole`, e.g.:
```json
"GroupToRole": {
"ot-operators": "WriteOperate",
"ot-tuners": "WriteTune",
"ot-engineers": "WriteConfigure",
"ot-alarm-ack": "AlarmAcknowledge",
"ot-readonly": "ReadOnly"
}
```
If this mapping is absent the data-plane evaluator is strictly default-deny: inbound operator
writes and OPC UA Part-9 alarm acknowledgement all return `BadUserAccessDenied` even for users who
authenticate successfully. (The same requirement gates the pre-existing scripted-alarm ack path.)
```
Also tighten line 163 (the `GroupToRole` description in the LDAP section) so it notes the values are control-plane **and** data-plane role strings, cross-referencing the new subsection — a one-clause edit, not a rewrite.
**Step 2: Verify the doc renders / no broken anchors, then commit**
```bash
git add docs/security.md
git commit -m "docs(security): document the GroupToRole data-plane role requirement"
```
(No test; verification = re-read the section for accuracy against the permission-flag names at lines 186-216.)
---
### Task T6: Galaxy writer — invalidate handle caches on reconnect
**Classification:** small
**Estimated implement time:** ~5 min
**Parallelizable with:** T1, T2, T3, T4, T5
Addresses pending.md #6(b).
**Files:**
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/IGalaxyDataWriter.cs` (interface — add method)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs` (caches 28-32; implement clear)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/TracedGalaxyDataWriter.cs` (decorator — delegate)
- Modify: `src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs` (`ReopenAsync` 291-296; `_dataWriter` set at 255-257)
- Test: `tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/` (GatewayGalaxyDataWriter test class)
**Context:** `GatewayGalaxyDataWriter` caches `_itemHandles` (ref→gw item handle, line 28) and `_supervisedHandles` (handle→advised, line 32). `_dataWriter` is built **once** in `BuildProductionRuntimeAsync` (255-257) and reused across reconnects. On reconnect, `ReopenAsync` (291-296) calls `_ownedMxSession.RecreateAsync` — which disposes + rebuilds the session, so all prior gw item handles are **dead**. The writer's caches still hold the stale handles, so a write right after a reconnect AddItem-skips and uses a dead handle. Add a cache-invalidation seam called on reopen.
**Step 1: Failing test — invalidation forces a fresh AddItem on the next write**
In the existing `GatewayGalaxyDataWriter` test class (it already constructs the writer over a fake/owned session — reuse that harness), add:
```csharp
[Fact]
public async Task InvalidateHandleCaches_forces_AddItem_again_on_next_write()
{
var (writer, fakeSession) = BuildWriterWithFakeSession(); // reuse existing harness
await writer.WriteAsync(new[] { new WriteRequest("Tag.Attr", 1) }, _ => SecurityClassification.Operate, default);
fakeSession.AddItemCallCount.ShouldBe(1);
writer.InvalidateHandleCaches();
await writer.WriteAsync(new[] { new WriteRequest("Tag.Attr", 2) }, _ => SecurityClassification.Operate, default);
fakeSession.AddItemCallCount.ShouldBe(2); // re-AddItem'd because the cache was cleared
}
```
If the existing fake session doesn't count `AddItem`, either extend it with a counter or assert via an internal seam on the writer (`internal int CachedItemHandleCount => _itemHandles.Count;`): assert `>0` after a write, `0` after `InvalidateHandleCaches()`. Pick whichever the existing harness makes cleanest.
**Step 2: Run — expect FAIL (no such method)**
```bash
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests --filter "FullyQualifiedName~InvalidateHandleCaches"
```
**Step 3: Add the method to the interface + impl + decorator**
- `IGalaxyDataWriter`: add
```csharp
/// <summary>Drop cached gw item handles + supervisory-advise state. Call after a session
/// reconnect — the old handles are dead, so the next write must re-AddItem + re-advise.</summary>
void InvalidateHandleCaches();
```
- `GatewayGalaxyDataWriter`:
```csharp
public void InvalidateHandleCaches()
{
_itemHandles.Clear();
_supervisedHandles.Clear();
}
```
- `TracedGalaxyDataWriter` (decorator): delegate — `public void InvalidateHandleCaches() => _inner.InvalidateHandleCaches();` (match the field name the decorator uses for its inner writer).
**Step 4: Call it on reopen**
In `GalaxyDriver.ReopenAsync` (291-296), after `RecreateAsync` succeeds:
```csharp
private async Task ReopenAsync(CancellationToken cancellationToken)
{
if (_ownedMxSession is null) return;
var clientOptions = BuildClientOptions(_options.Gateway);
await _ownedMxSession.RecreateAsync(clientOptions, cancellationToken).ConfigureAwait(false);
// The recreated session invalidates every prior gw item handle; drop the writer's handle/advise
// caches so the next write re-AddItems + re-AdviseSupervisory against the fresh session.
_dataWriter?.InvalidateHandleCaches();
}
```
(`_dataWriter` is the `TracedGalaxyDataWriter`-wrapped field set at 255-257; the call flows through to the inner `GatewayGalaxyDataWriter`.)
**Step 5: Run — expect PASS, run the full Galaxy suite, build**
```bash
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests --filter "FullyQualifiedName~InvalidateHandleCaches"
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests
```
**Step 6: Commit (stage by path)**
```bash
git add src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/ tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/
git commit -m "fix(galaxy): invalidate writer handle caches on session reconnect"
```
---
## Final verification (after T1–T6)
```bash
dotnet build ZB.MOM.WW.OtOpcUa.slnx # 0 errors (TreatWarningsAsErrors)
dotnet test tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.FOCAS.Tests
dotnet test tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests
```
These are all unit-level changes (no live docker-dev `/run` gate needed — none touch Razor/JS or the wire protocol behaviourally; the fast-fail paths and cache changes are exercised by Akka.TestKit + unit tests). Then finish via **superpowers-extended-cc:finishing-a-development-branch** (intent: merge-to-master + push). After merge, update `pending.md` to mark #3, #4, #6 resolved.
## Out of scope (left in pending.md)
- #4 sub-item: FOCAS — covered (T3). The "surface real device-write status" item (#5) is a **separate** chosen-later effort, not part of this cluster.
- #7 driver-reconfigure-while-faulted — its own high-risk actor-state-machine design/plan.
- #1/#2 Phase B/C; #8 rig cleanups — unchanged.
@@ -0,0 +1,13 @@
{
"planPath": "docs/plans/2026-06-14-harden-milestone-1b-plan.md",
"tasks": [
{"id": "354", "subject": "T0: Create feature branch chore/harden-milestone-1b", "classification": "trivial", "status": "completed"},
{"id": "355", "subject": "T1: DriverHostActor Stale write fast-fail + micro-opts + raw-blob routing test", "classification": "standard", "status": "completed", "blockedBy": ["354"], "commits": ["4cda275b", "99eea0b4"]},
{"id": "356", "subject": "T2: DriverInstanceActor degraded-state write fast-fail + benign SubscriptionEstablished handler", "classification": "standard", "status": "completed", "blockedBy": ["354"], "commits": ["42b4a923", "7e405e94"]},
{"id": "357", "subject": "T3: FOCAS cache equipment-tag parsed addresses", "classification": "small", "status": "completed", "blockedBy": ["354"], "commits": ["46f559f5"]},
{"id": "358", "subject": "T4: Parity test future-enum trap InlineData(2,false)", "classification": "trivial", "status": "completed", "blockedBy": ["354"], "commits": ["97d82dda"]},
{"id": "359", "subject": "T5: docs/security.md data-plane GroupToRole requirement note", "classification": "trivial", "status": "completed", "blockedBy": ["354"], "commits": ["190ef34e"]},
{"id": "360", "subject": "T6: Galaxy writer invalidate handle caches on reconnect", "classification": "small", "status": "completed", "blockedBy": ["354"], "commits": ["f77488ee"]}
],
"lastUpdated": "2026-06-14"
}
+24 -1
View File
@@ -160,7 +160,7 @@ LDAP is configured under the `Security:Ldap` section (bound to `LdapOptions`, `s
}
```
`GroupToRole` maps LDAP group names → Admin roles (case-insensitive); a user gets every role whose source group is in their membership. The values are the canonical control-plane role strings (`Viewer` / `Designer` / `Administrator`, plus the appsettings-only `Operator` for the `DriverOperator` policy). `UserNameAttribute: "sAMAccountName"` is the critical AD override — the GLAuth dev default is `cn`, which is not how AD users are looked up; use `userPrincipalName` instead if operators log in with `user@corp.example.com` form. `LdapOptionsValidator` (`src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs`) fails startup when `Transport = None` and `AllowInsecure = false` on a real-LDAP (non-DevStub) config.
`GroupToRole` maps LDAP group names → roles (case-insensitive); a user gets every role whose source group is in their membership. The values are the canonical control-plane role strings (`Viewer` / `Designer` / `Administrator`, plus the appsettings-only `Operator` for the `DriverOperator` policy); the same map also supplies data-plane role strings (`ReadOnly`, `WriteOperate`, `WriteTune`, `WriteConfigure`, `AlarmAcknowledge`) — see [Role grant source (data-plane)](#role-grant-source-data-plane) below. `UserNameAttribute: "sAMAccountName"` is the critical AD override — the GLAuth dev default is `cn`, which is not how AD users are looked up; use `userPrincipalName` instead if operators log in with `user@corp.example.com` form. `LdapOptionsValidator` (`src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/LdapOptionsValidator.cs`) fails startup when `Transport = None` and `AllowInsecure = false` on a real-LDAP (non-DevStub) config.
---
@@ -242,6 +242,29 @@ Key properties:
See [`docs/v2/acl-design.md`](v2/acl-design.md) for the complete design: trie invalidation, flag semantics, per-path override rules, and the reasoning behind additive-only (no Deny).
### Role grant source (data-plane)
Data-plane roles come from `Security:Ldap:GroupToRole` (appsettings), **not** from the Config-DB
`LdapGroupRoleMapping` table. That table's `Role` column is the `AdminRole` enum
(`Administrator`/`Designer`/`Viewer`) and supplies **control-plane** roles only — it cannot emit the
data-plane role strings the OPC UA gates read (`ReadOnly`, `WriteOperate`, `WriteTune`,
`WriteConfigure`, `AlarmAcknowledge`). A deployment therefore **must** map its data-plane LDAP groups
to those role strings via `GroupToRole`, e.g.:
```json
"GroupToRole": {
"ot-operators": "WriteOperate",
"ot-tuners": "WriteTune",
"ot-engineers": "WriteConfigure",
"ot-alarm-ack": "AlarmAcknowledge",
"ot-readonly": "ReadOnly"
}
```
If this mapping is absent the data-plane evaluator is strictly default-deny: inbound operator writes
and OPC UA Part-9 alarm acknowledgement all return `BadUserAccessDenied` even for users who
authenticate successfully. (The same requirement gates the pre-existing scripted-alarm ack path.)
---
## Control-Plane Authorization
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
@@ -33,8 +34,10 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
private readonly EquipmentTagRefResolver<FocasTagDefinition> _resolver;
// Per-tag-name cache of the FocasAddress parsed once at InitializeAsync. ReadAsync /
// WriteAsync look up the pre-parsed value instead of re-parsing tag.Address on every hot
// call — resolves Driver.FOCAS-008.
private readonly Dictionary<string, FocasAddress> _parsedAddressesByTagName =
// call — resolves Driver.FOCAS-008. ConcurrentDictionary is required because the poll loop
// (ReadAsync) and the host write thread (WriteAsync) both mutate this cache when resolver-
// produced equipment tags are encountered for the first time.
private readonly ConcurrentDictionary<string, FocasAddress> _parsedAddressesByTagName =
new(StringComparer.OrdinalIgnoreCase);
private FocasAlarmProjection? _alarmProjection;
// _health is read/written from multiple threads (ReadAsync, WriteAsync, ProbeLoopAsync).
@@ -230,6 +233,23 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
/// <summary>Test seam — the resolved options the factory built this driver from.</summary>
internal FocasDriverOptions Options => _options;
/// <summary>Test seam — returns true when a parsed <see cref="FocasAddress"/> for the given
/// reference is present in the address cache (both authored and equipment-tag paths).</summary>
internal bool IsParsedAddressCached(string reference) =>
_parsedAddressesByTagName.ContainsKey(reference);
// Resolves a tag definition to its parsed FocasAddress, caching the result so that
// equipment tags (resolver-produced, not seeded at InitializeAsync) don't re-parse the
// address string on every ReadAsync / WriteAsync hot-path call (Driver.FOCAS-008).
// Throwing inside the GetOrAdd factory propagates the exception to the caller and does
// NOT store anything in the dictionary — consistent with the existing "fail fast on a
// malformed address" behaviour from the init-time validation of authored tags.
private FocasAddress ResolveParsedAddress(FocasTagDefinition def) =>
_parsedAddressesByTagName.GetOrAdd(def.Name, _ =>
FocasAddress.TryParse(def.Address)
?? throw new InvalidOperationException(
$"FOCAS tag '{def.Name}' has malformed Address '{def.Address}'."));
// ---- IReadable ----
/// <summary>Reads values from one or more tags asynchronously.</summary>
@@ -270,14 +290,7 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
try
{
var client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false);
// Parsed at InitializeAsync — defensive fallback re-parse only if the tag was
// somehow not seeded (shouldn't happen, but keeps the call total).
if (!_parsedAddressesByTagName.TryGetValue(def.Name, out var parsed))
{
parsed = FocasAddress.TryParse(def.Address)
?? throw new InvalidOperationException(
$"FOCAS tag '{def.Name}' has malformed Address '{def.Address}'.");
}
var parsed = ResolveParsedAddress(def);
var (value, status) = await client.ReadAsync(parsed, def.DataType, cancellationToken).ConfigureAwait(false);
results[i] = new DataValueSnapshot(value, status, now, now);
@@ -334,12 +347,7 @@ public sealed class FocasDriver : IDriver, IReadable, IWritable, ITagDiscovery,
try
{
var client = await EnsureConnectedAsync(device, cancellationToken).ConfigureAwait(false);
if (!_parsedAddressesByTagName.TryGetValue(def.Name, out var parsed))
{
parsed = FocasAddress.TryParse(def.Address)
?? throw new InvalidOperationException(
$"FOCAS tag '{def.Name}' has malformed Address '{def.Address}'.");
}
var parsed = ResolveParsedAddress(def);
var status = await client.WriteAsync(parsed, def.DataType, w.Value, cancellationToken).ConfigureAwait(false);
results[i] = new WriteResult(status);
}
@@ -293,6 +293,9 @@ public sealed class GalaxyDriver
if (_ownedMxSession is null) return;
var clientOptions = BuildClientOptions(_options.Gateway);
await _ownedMxSession.RecreateAsync(clientOptions, cancellationToken).ConfigureAwait(false);
// The recreated session invalidates every prior gw item handle; drop the writer's handle/advise
// caches so the next write re-AddItems + re-AdviseSupervisory against the fresh session.
_dataWriter?.InvalidateHandleCaches();
}
/// <summary>
@@ -42,6 +42,42 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
_logger = logger ?? NullLogger.Instance;
}
/// <inheritdoc />
public void InvalidateHandleCaches()
{
_itemHandles.Clear();
_supervisedHandles.Clear();
}
// ===== Test seams (internal — not part of the public contract) =====
/// <summary>
/// Count of item-handle cache entries. Zero on a fresh instance or immediately after
/// <see cref="InvalidateHandleCaches"/>. Used by unit tests to verify cache state
/// without running a real gRPC round-trip.
/// </summary>
internal int CachedItemHandleCount => _itemHandles.Count;
/// <summary>
/// Count of supervisory-advised handle entries. Zero on a fresh instance or immediately
/// after <see cref="InvalidateHandleCaches"/>. Used by unit tests to verify cache state.
/// </summary>
internal int CachedSupervisedHandleCount => _supervisedHandles.Count;
/// <summary>
/// Pre-populate both caches as if a write had already occurred. Used by unit tests to
/// simulate the "post-write" state without running a real gRPC gateway session (the SDK
/// session types are sealed + internal-ctor and cannot be faked).
/// </summary>
/// <param name="fullRef">The tag full reference to add to the item-handle cache.</param>
/// <param name="itemHandle">The item handle to cache for that reference.</param>
/// <param name="supervised">When true, also records the handle in the supervised-handle cache.</param>
internal void SeedHandleCachesForTest(string fullRef, int itemHandle, bool supervised)
{
_itemHandles[fullRef] = itemHandle;
if (supervised) _supervisedHandles.TryAdd(itemHandle, 0);
}
/// <summary>Writes values to Galaxy tags through the gateway.</summary>
/// <param name="writes">The write requests.</param>
/// <param name="securityResolver">Function to resolve security classification per tag.</param>
@@ -30,4 +30,8 @@ public interface IGalaxyDataWriter
IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver,
CancellationToken cancellationToken);
/// <summary>Drop cached gateway item handles + supervisory-advise state. Call after a session
/// reconnect — the prior handles are dead, so the next write must re-AddItem + re-AdviseSupervisory.</summary>
void InvalidateHandleCaches();
}
@@ -10,6 +10,10 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
/// </summary>
internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string clientName) : IGalaxyDataWriter
{
/// <inheritdoc />
/// <remarks>No span — this is a local cache-clear operation, not a gateway round-trip.</remarks>
public void InvalidateHandleCaches() => inner.InvalidateHandleCaches();
/// <summary>Writes data to Galaxy while recording telemetry span.</summary>
/// <param name="writes">The list of write requests to process.</param>
/// <param name="securityResolver">Function to resolve security classification for tag references.</param>
@@ -92,10 +92,11 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
/// NodeId(s)</c>. Rebuilt every apply by <see cref="PushDesiredSubscriptions"/> from the
/// composition's <c>EquipmentTags</c> (mirroring <c>VirtualTagHostActor._nodeIdByVtag</c>), and
/// resolved in <see cref="ForwardToMux"/> so a driver value published by wire-ref FullName lands
/// on the variable's actual folder-scoped NodeId. A list because the same driver ref can back
/// several equipment variables (e.g. identical machines sharing a register).
/// on the variable's actual folder-scoped NodeId. A set because the same driver ref can back
/// several equipment variables (e.g. identical machines sharing a register), and the per-apply
/// rebuild dedups by NodeId.
/// </summary>
private readonly Dictionary<(string DriverInstanceId, string FullName), List<string>> _nodeIdByDriverRef = new();
private readonly Dictionary<(string DriverInstanceId, string FullName), HashSet<string>> _nodeIdByDriverRef = new();
/// <summary>
/// Inverse of <see cref="_nodeIdByDriverRef"/>: <c>folder-scoped equipment NodeId →
@@ -516,7 +517,7 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
? new NodeWriteResult(t.Result.Success, t.Result.Reason)
: new NodeWriteResult(false, "write timeout"),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskContinuationOptions.None,
TaskScheduler.Default)
.PipeTo(replyTo);
}
@@ -545,6 +546,10 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
Receive<RestartDriver>(HandleRestartDriver);
Receive<ReconnectDriver>(HandleReconnectDriver);
Receive<RedundancyStateChanged>(OnRedundancyStateChanged);
// An inbound operator write can't be serviced while the config DB is unreachable — fast-fail so the
// node-manager's bounded Ask gets an immediate clear status instead of dead-lettering into a timeout.
Receive<RouteNodeWrite>(_ =>
Sender.Tell(new NodeWriteResult(false, "driver host stale (config DB unreachable)")));
Receive<SubscribeAck>(_ => { /* PubSub ack */ });
Timers.StartPeriodicTimer("retry-db", RetryConfigDbConnection.Instance, ReconnectInterval);
}
@@ -751,9 +756,9 @@ public sealed class DriverHostActor : ReceiveActor, IWithTimers
{
var key = (t.DriverInstanceId, t.FullName);
var nodeId = EquipmentNodeIds.Variable(t.EquipmentId, t.FolderPath, t.Name);
if (!_nodeIdByDriverRef.TryGetValue(key, out var list))
_nodeIdByDriverRef[key] = list = new List<string>();
if (!list.Contains(nodeId)) list.Add(nodeId);
if (!_nodeIdByDriverRef.TryGetValue(key, out var set))
_nodeIdByDriverRef[key] = set = new HashSet<string>(StringComparer.Ordinal);
set.Add(nodeId);
_driverRefByNodeId[nodeId] = key;
}
@@ -211,6 +211,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
private void Connecting()
{
Receive<InitializeRequested>(msg => InitializeAsync(msg.DriverConfigJson));
// Fast-fail writes while still connecting — without this the inbound WriteAttribute dead-letters
// and DriverHostActor.HandleRouteNodeWrite waits its full 8s Ask before reporting a generic
// "write timeout". Synchronous Receive: Sender.Tell on the actor thread is safe (#4a-instance).
Receive<WriteAttribute>(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive<InitializeSucceeded>(_ =>
{
_log.Info("DriverInstance {Id}: connected", _driverInstanceId);
@@ -227,6 +232,15 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
});
Receive<SetDesiredSubscriptions>(StoreDesiredSubscriptions);
Receive<ForceReconnect>(_ => { /* already connecting — no-op */ });
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive<SubscriptionEstablished>(msg =>
_log.Debug("DriverInstance {Id}: subscription established ({Count} refs, {Diag})",
_driverInstanceId, msg.ReferenceCount, msg.DiagnosticId));
// Symmetric to the SubscriptionEstablished swallow: a failed self-resubscribe replies SubscriptionFailed
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive<SubscriptionFailed>(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
Receive<HealthPollTick>(_ => PublishHealthSnapshot());
}
@@ -259,12 +273,25 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
else if (_subscriptionHandle is not null) Self.Tell(new Unsubscribe());
});
Receive<DataChangeForward>(OnDataChangeForward);
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive<SubscriptionEstablished>(msg =>
_log.Debug("DriverInstance {Id}: subscription established ({Count} refs, {Diag})",
_driverInstanceId, msg.ReferenceCount, msg.DiagnosticId));
// Symmetric to the SubscriptionEstablished swallow: a failed self-resubscribe replies SubscriptionFailed
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive<SubscriptionFailed>(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
Receive<HealthPollTick>(_ => PublishHealthSnapshot());
}
private void Reconnecting()
{
Receive<RetryConnect>(_ => InitializeAsync(_currentConfigJson ?? "{}"));
// Fast-fail writes while reconnecting (same reason as Connecting — avoids the 8s host Ask
// timeout on an inbound write to a transiently-down driver). Synchronous Receive (#4a-instance).
Receive<WriteAttribute>(_ =>
Sender.Tell(new WriteAttributeResult(false, "driver not connected")));
Receive<InitializeSucceeded>(_ =>
{
Timers.Cancel("retry-connect");
@@ -276,6 +303,15 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
Receive<InitializeFailed>(_ => { /* keep retrying via timer */ });
Receive<SetDesiredSubscriptions>(StoreDesiredSubscriptions);
Receive<ForceReconnect>(_ => { /* already reconnecting — no-op */ });
// ResubscribeDesired self-Tells Subscribe; HandleSubscribeAsync replies SubscriptionEstablished to the
// sender, which on the self-resubscribe path is Self. Swallow it (trace only) so it doesn't dead-letter.
Receive<SubscriptionEstablished>(msg =>
_log.Debug("DriverInstance {Id}: subscription established ({Count} refs, {Diag})",
_driverInstanceId, msg.ReferenceCount, msg.DiagnosticId));
// Symmetric to the SubscriptionEstablished swallow: a failed self-resubscribe replies SubscriptionFailed
// to Self (HandleSubscribeAsync already logged the underlying cause). Swallow it so it doesn't dead-letter.
Receive<SubscriptionFailed>(msg =>
_log.Debug("DriverInstance {Id}: resubscribe reported failure: {Reason}", _driverInstanceId, msg.Reason));
Receive<HealthPollTick>(_ => PublishHealthSnapshot());
Timers.StartPeriodicTimer("retry-connect", RetryConnect.Instance, _reconnectInterval);
}
@@ -64,4 +64,35 @@ public class FocasEquipmentTagTests
r[0].StatusCode.ShouldNotBe(FocasStatusMapper.BadNodeIdUnknown);
r[0].Value.ShouldBe((sbyte)42);
}
/// <summary>
/// Regression guard for Driver.FOCAS-008 equipment-tag path: the parsed
/// <see cref="FocasAddress"/> for a resolver-produced (equipment) tag must be
/// cached after the first read so subsequent reads and writes skip re-parsing
/// the raw TagConfig JSON on every call.
/// </summary>
[Fact]
public async Task Equipment_tag_parsed_address_is_cached_after_first_read()
{
var equipRef = """{"deviceHostAddress":"focas://10.0.0.5:8193","address":"R100","dataType":"Byte"}""";
var factory = new FakeFocasClientFactory
{
Customise = () => new FakeFocasClient { Values = { ["R100"] = (sbyte)7 } },
};
var drv = new FocasDriver(new FocasDriverOptions
{
Devices = [new FocasDeviceOptions("focas://10.0.0.5:8193")],
Tags = [],
Probe = new FocasProbeOptions { Enabled = false },
}, "focas-eq-cache", factory);
await drv.InitializeAsync("{}", CancellationToken.None);
// Before any read the parsed address must NOT be in the cache.
drv.IsParsedAddressCached(equipRef).ShouldBeFalse();
// After a successful read the parsed address MUST be cached.
var r = await drv.ReadAsync([equipRef], CancellationToken.None);
r[0].StatusCode.ShouldBe(FocasStatusMapper.Good);
drv.IsParsedAddressCached(equipRef).ShouldBeTrue();
}
}
@@ -94,6 +94,9 @@ public sealed class GalaxyDriverWriteTests
}
return Task.FromResult<IReadOnlyList<WriteResult>>(results);
}
/// <inheritdoc />
public void InvalidateHandleCaches() { /* no-op — this fake has no handle caches */ }
}
private static GalaxyAttribute Attr(string name, int sec)
@@ -178,6 +178,9 @@ public sealed class GalaxyTelemetryTests
CancellationToken cancellationToken)
=> Task.FromResult<IReadOnlyList<WriteResult>>(
writes.Select(_ => new WriteResult(0u)).ToList());
/// <inheritdoc />
public void InvalidateHandleCaches() { /* no-op — this fake has no handle caches */ }
}
private sealed class FakeHierarchy : IGalaxyHierarchySource
@@ -0,0 +1,91 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// Tests for <see cref="GatewayGalaxyDataWriter.InvalidateHandleCaches"/>.
/// The SDK session types are sealed with internal ctors and cannot be faked, so we
/// drive the cache-seeding path through
/// <see cref="GatewayGalaxyDataWriter.SeedHandleCachesForTest"/> and verify the
/// handle-count seams — the contract under test is purely that
/// <see cref="GatewayGalaxyDataWriter.InvalidateHandleCaches"/> zeroes both dictionaries
/// so the next write is forced to re-AddItem + re-AdviseSupervisory.
/// </summary>
public sealed class GatewayGalaxyDataWriterTests
{
private static GalaxyMxSession MinimalSession()
=> new(new GalaxyMxAccessOptions(ClientName: "OtOpcUa-Test"));
/// <summary>
/// Approach (b): seed the item-handle cache directly via the internal test seam,
/// confirm the count is positive, call <see cref="GatewayGalaxyDataWriter.InvalidateHandleCaches"/>,
/// and confirm both caches are cleared.
/// The next write (not simulated here — needs a live gw) would therefore be forced
/// to re-AddItem because the cache is empty.
/// </summary>
[Fact]
public void InvalidateHandleCaches_clears_item_and_supervised_handle_caches()
{
var session = MinimalSession();
var writer = new GatewayGalaxyDataWriter(session, writeUserId: 0);
// Pre-seed both caches via the internal test seam so we can assert the
// "after a write" state without spinning up a real gRPC gateway session.
writer.SeedHandleCachesForTest("TestMachine_001.TestAttr", itemHandle: 42, supervised: true);
writer.CachedItemHandleCount.ShouldBe(1);
writer.CachedSupervisedHandleCount.ShouldBe(1);
writer.InvalidateHandleCaches();
writer.CachedItemHandleCount.ShouldBe(0);
writer.CachedSupervisedHandleCount.ShouldBe(0);
}
/// <summary>
/// A second seed + invalidate cycle proves the method isn't one-shot — a reconnect
/// followed by writes followed by another reconnect must also start fresh.
/// </summary>
[Fact]
public void InvalidateHandleCaches_is_repeatable_across_multiple_reconnects()
{
var session = MinimalSession();
var writer = new GatewayGalaxyDataWriter(session, writeUserId: 0);
// First session cycle
writer.SeedHandleCachesForTest("Tag.A", itemHandle: 1, supervised: false);
writer.SeedHandleCachesForTest("Tag.B", itemHandle: 2, supervised: true);
writer.CachedItemHandleCount.ShouldBe(2);
writer.InvalidateHandleCaches();
writer.CachedItemHandleCount.ShouldBe(0);
writer.CachedSupervisedHandleCount.ShouldBe(0);
// Second session cycle — handles re-populated after the reconnect's replay
writer.SeedHandleCachesForTest("Tag.A", itemHandle: 99, supervised: true);
writer.CachedItemHandleCount.ShouldBe(1);
writer.InvalidateHandleCaches();
writer.CachedItemHandleCount.ShouldBe(0);
}
/// <summary>
/// <see cref="GatewayGalaxyDataWriter.InvalidateHandleCaches"/> on a fresh (never-used)
/// writer must be a no-op rather than throwing — the reconnect supervisor may call it
/// before any write has occurred.
/// </summary>
[Fact]
public void InvalidateHandleCaches_on_empty_caches_is_a_noop()
{
var session = MinimalSession();
var writer = new GatewayGalaxyDataWriter(session, writeUserId: 0);
// Caches are empty — must not throw.
writer.CachedItemHandleCount.ShouldBe(0);
writer.CachedSupervisedHandleCount.ShouldBe(0);
writer.InvalidateHandleCaches();
writer.CachedItemHandleCount.ShouldBe(0);
writer.CachedSupervisedHandleCount.ShouldBe(0);
}
}
@@ -73,6 +73,7 @@ public sealed class DeploymentArtifactAliasParityTests
[Theory]
[InlineData(1, true)] // numeric ReadWrite
[InlineData(0, false)] // numeric Read
[InlineData(2, false)] // future/unknown AccessLevel maps fail-safe to read-only (only ReadWrite==1 ⇒ writable)
public void ParseComposition_maps_numeric_AccessLevel_to_Writable(int accessLevel, bool expectedWritable)
{
var blob = JsonSerializer.SerializeToUtf8Bytes(new
@@ -125,6 +125,64 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
recorder.Writes.ShouldBeEmpty();
}
/// <summary>A protocol TagConfig blob with no <c>FullName</c> key routes by the equipment NodeId, and
/// the forwarded wire-ref is the raw blob verbatim. <c>ExtractTagFullName</c> falls back to the raw
/// blob string when no top-level <c>FullName</c> property is present, so the reverse map keys on
/// <c>(DriverInstanceId, &lt;raw-blob&gt;)</c> and the driver receives that exact string as its
/// <c>WriteRequest.FullReference</c> — not a FullName value extracted from the blob.</summary>
[Fact]
public void Primary_routes_write_for_raw_protocol_blob_tag()
{
var db = NewInMemoryDbFactory();
var recorder = new RecordingDriverFactory("Modbus");
// Seed the tag with a genuine protocol blob that has NO FullName key (pure Modbus wire config).
// ExtractTagFullName falls back to returning the raw blob string verbatim, so that string IS the
// wire-ref the reverse map keys on and the driver receives as WriteRequest.FullReference.
var (deploymentId, rawBlobString) = SeedDeploymentWithRawBlobTag(db, RevA,
equip: "eq-2", driver: "drv-2", name: "torque");
var actor = SpawnHostAndApply(db, deploymentId, recorder);
// Local role unknown ⇒ treated as Primary ⇒ write allowed.
var asker = CreateTestProbe();
actor.Tell(new DriverHostActor.RouteNodeWrite("eq-2/torque", 456.0), asker.Ref);
var result = asker.ExpectMsg<DriverHostActor.NodeWriteResult>(Timeout);
result.Success.ShouldBeTrue();
// The forwarded wire-ref is the raw blob string verbatim — ExtractTagFullName fell back because
// there is no top-level "FullName" key in the blob.
AwaitAssert(() =>
{
recorder.Writes.Count.ShouldBe(1);
recorder.Writes[0].FullReference.ShouldBe(rawBlobString);
recorder.Writes[0].Value.ShouldBe(456.0);
}, duration: Timeout);
}
/// <summary>A RouteNodeWrite arriving while the host is Stale (config DB unreachable) must fast-fail
/// with an immediate negative NodeWriteResult (reason mentions "stale") instead of dead-lettering into
/// the node-manager's bounded-Ask timeout. Drives the host into Stale via a DB factory whose
/// CreateDbContext throws on bootstrap (the same fall-through to <c>Become(Stale)</c> production uses).</summary>
[Fact]
public void Stale_host_fast_fails_route_node_write()
{
// A factory that always throws on CreateDbContext ⇒ Bootstrap's try fails ⇒ Become(Stale).
var db = new ThrowingDbFactory();
var coordinator = CreateTestProbe();
var actor = Sys.ActorOf(DriverHostActor.Props(
db, TestNode, coordinator.Ref,
localRoles: new HashSet<string> { "driver" }));
var asker = CreateTestProbe();
actor.Tell(new DriverHostActor.RouteNodeWrite("eq-1/speed", 123.0), asker.Ref);
var result = asker.ExpectMsg<DriverHostActor.NodeWriteResult>(TimeSpan.FromSeconds(2));
result.Success.ShouldBeFalse();
result.Reason.ShouldNotBeNull();
result.Reason!.ShouldContain("stale");
}
/// <summary>Spawns the host with the recording driver factory, dispatches the deployment, and waits
/// for the Applied ACK so the apply (and thus the reverse-map build in PushDesiredSubscriptions) has
/// completed before the test routes a write. No OPC UA / mux probes are wired — this test exercises
@@ -200,6 +258,84 @@ public sealed class DriverHostActorWriteRoutingTests : RuntimeActorTestBase
return id;
}
/// <summary>
/// Seeds a single-tag Sealed deployment whose tag's <c>TagConfig</c> is a genuine protocol-driver
/// blob with <strong>no <c>FullName</c> key</strong> (pure Modbus wire config:
/// <c>{"region":"HoldingRegister","address":200,"dataType":"UInt16"}</c>). Because
/// <c>ExtractTagFullName</c> finds no top-level <c>FullName</c> property, it falls back to
/// returning the raw blob string verbatim — that raw string becomes the
/// <c>(DriverInstanceId, &lt;raw-blob&gt;)</c> reverse-map key, and the driver receives it as
/// <c>WriteRequest.FullReference</c>. Returns both the <see cref="DeploymentId"/> and the exact
/// raw blob string so the caller can assert the forwarded wire-ref precisely.
/// </summary>
private static (DeploymentId DeploymentId, string RawBlobString) SeedDeploymentWithRawBlobTag(
IDbContextFactory<OtOpcUaConfigDbContext> db, RevisionHash rev,
string equip, string driver, string name)
{
// Serialize the blob with NO FullName field — ExtractTagFullName will fall back to this verbatim.
var rawBlobString = JsonSerializer.Serialize(
new { region = "HoldingRegister", address = 200, dataType = "UInt16" });
var artifact = JsonSerializer.SerializeToUtf8Bytes(new
{
Namespaces = new[]
{
new { NamespaceId = "ns-eq", Kind = 0 }, // NamespaceKind.Equipment = 0
},
DriverInstances = new[]
{
new
{
DriverInstanceRowId = Guid.NewGuid(),
DriverInstanceId = driver,
Name = driver,
DriverType = "Modbus", // not Windows-only ⇒ a real child is spawned (not stubbed)
Enabled = true,
DriverConfig = "{}",
NamespaceId = "ns-eq",
},
},
Tags = new[]
{
new
{
TagId = "tag-raw",
EquipmentId = equip,
DriverInstanceId = driver,
Name = name,
FolderPath = (string?)null,
DataType = "Double",
// Pure protocol blob: no FullName key. ExtractTagFullName falls back to raw blob.
TagConfig = rawBlobString,
},
},
});
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, rawBlobString);
}
/// <summary>An <see cref="IDbContextFactory{TContext}"/> whose <c>CreateDbContext</c> always throws,
/// driving <see cref="DriverHostActor"/>'s bootstrap into the <c>catch</c> ⇒ <c>Become(Stale)</c> path
/// so a write can be routed at a Stale host.</summary>
private sealed class ThrowingDbFactory : IDbContextFactory<OtOpcUaConfigDbContext>
{
/// <inheritdoc />
public OtOpcUaConfigDbContext CreateDbContext() =>
throw new InvalidOperationException("config DB unreachable (test stub)");
}
/// <summary>Factory producing a single <see cref="RecordingDriver"/> for the supported type, whose
/// recorded write list is exposed for assertions.</summary>
private sealed class RecordingDriverFactory : IDriverFactory
@@ -0,0 +1,313 @@
using Akka.Actor;
using Akka.Event;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.Drivers;
/// <summary>
/// Covers two robustness nits on the generic <see cref="DriverInstanceActor"/>:
/// (1) writes that arrive while the actor is NOT in <c>Connected</c> (Stubbed / Connecting /
/// Reconnecting) must fast-fail with a negative <see cref="DriverInstanceActor.WriteAttributeResult"/>
/// rather than dead-letter and let the host Ask wait its full 8s timeout; and
/// (2) the self-Tell <c>Subscribe</c> issued by <c>ResubscribeDesired</c> on (re)connect must not
/// leave a stray <see cref="DriverInstanceActor.SubscriptionEstablished"/> dead-lettering when its
/// reply lands back at Self.
/// </summary>
public sealed class DriverInstanceActorWriteAndSubscribeTests : RuntimeActorTestBase
{
/// <summary>
/// A write to a Stubbed actor fast-fails synchronously: a Stubbed driver never connects, yet
/// it must answer a <see cref="DriverInstanceActor.WriteAttribute"/> Ask with a negative result
/// well inside the host's 8s timeout instead of dead-lettering.
/// </summary>
[Fact]
public async Task WriteAttribute_to_stubbed_driver_fast_fails()
{
var driver = new WritableStubDriver();
var actor = Sys.ActorOf(DriverInstanceActor.Props(driver, startStubbed: true));
var reply = await actor.Ask<DriverInstanceActor.WriteAttributeResult>(
new DriverInstanceActor.WriteAttribute("tag-1", 42),
TimeSpan.FromSeconds(2));
// Stubbed drivers deterministically succeed writes without touching hardware (existing behaviour).
reply.Success.ShouldBeTrue();
}
/// <summary>
/// A write to a Connecting actor (InitializeAsync still in flight, never resolves) fast-fails
/// with <c>Success=false</c> and a non-null reason in well under the 8s host Ask timeout —
/// proving the synchronous fast-fail in <c>Connecting()</c> fires instead of dead-lettering.
/// </summary>
[Fact]
public async Task WriteAttribute_to_connecting_driver_fast_fails()
{
// BlockingInitDriver.InitializeAsync never completes, so the actor stays in Connecting.
var driver = new BlockingInitDriver();
var actor = Sys.ActorOf(DriverInstanceActor.Props(driver));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
AwaitCondition(() => driver.InitializeStarted, TimeSpan.FromSeconds(2));
var sw = System.Diagnostics.Stopwatch.StartNew();
var reply = await actor.Ask<DriverInstanceActor.WriteAttributeResult>(
new DriverInstanceActor.WriteAttribute("tag-1", 42),
TimeSpan.FromSeconds(2));
sw.Stop();
reply.Success.ShouldBeFalse();
reply.Reason.ShouldNotBeNull();
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(2));
}
/// <summary>
/// A write to a Reconnecting actor (initial connect failed, retrying) fast-fails with a negative
/// result rather than dead-lettering and hanging the host Ask.
/// </summary>
[Fact]
public async Task WriteAttribute_to_reconnecting_driver_fast_fails()
{
// InitializeShouldThrow drives Connecting → Reconnecting; the slow reconnect interval keeps it
// parked there long enough to take a write.
var driver = new WritableStubDriver { InitializeShouldThrow = true };
var actor = Sys.ActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromSeconds(30)));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
// The first Initialize attempt throws and pushes the actor into Reconnecting.
AwaitCondition(() => driver.InitializeCount >= 1, TimeSpan.FromSeconds(2));
var reply = await actor.Ask<DriverInstanceActor.WriteAttributeResult>(
new DriverInstanceActor.WriteAttribute("tag-1", 42),
TimeSpan.FromSeconds(2));
reply.Success.ShouldBeFalse();
reply.Reason.ShouldNotBeNull();
}
/// <summary>
/// Driving a connect + auto-resubscribe cycle (the self-Tell <c>Subscribe</c> from
/// <c>ResubscribeDesired</c> whose <c>SubscriptionEstablished</c> reply lands at Self) must not
/// produce a <see cref="DriverInstanceActor.SubscriptionEstablished"/> dead-letter.
/// </summary>
[Fact]
public async Task Self_resubscribe_does_not_deadletter_SubscriptionEstablished()
{
// The probe IGNORES every DeadLetter except those carrying a SubscriptionEstablished payload,
// so its mailbox only ever holds the message we care about. That makes the assertion precise:
// any swallow miss surfaces as a SubscriptionEstablished DeadLetter, and nothing else
// (health-poll cruft, remoting-terminator letters) can give a false positive.
var deadLetters = CreateTestProbe();
deadLetters.IgnoreMessages(m => m is not AllDeadLetters { Message: DriverInstanceActor.SubscriptionEstablished });
Sys.EventStream.Subscribe(deadLetters.Ref, typeof(AllDeadLetters));
var driver = new SubscribableStubDriver();
var actor = Sys.ActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromMilliseconds(50)));
// Desired set arrives first; on connect, ResubscribeDesired self-Tells Subscribe, whose
// SubscriptionEstablished reply lands at Self.
actor.Tell(new DriverInstanceActor.SetDesiredSubscriptions(
new[] { "tag-a", "tag-b" }, TimeSpan.FromMilliseconds(100)));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
AwaitCondition(() => driver.SubscribeCount >= 1, TimeSpan.FromSeconds(2));
// Force a reconnect to exercise the resubscribe path a second time.
actor.Tell(new DriverInstanceActor.DisconnectObserved("backend blip"));
AwaitCondition(() => driver.SubscribeCount >= 2, TimeSpan.FromSeconds(3));
// BARRIER: the self-resubscribe reply is published asynchronously, so SubscribeCount>=2 alone
// doesn't guarantee the actor has yet PROCESSED the self-sent SubscriptionEstablished (the point
// where it either swallows it or — pre-fix — dead-letters it). Drive a real Subscribe Ask from
// the TEST and await its reply: Akka processes the mailbox in order, so once this round-trips,
// every earlier self-resubscribe reply has already been handled and any dead-letter has already
// been published to the EventStream (Unhandled publishes synchronously). Only THEN is ExpectNoMsg
// race-free.
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
new DriverInstanceActor.Subscribe(new[] { "tag-a", "tag-b" }, TimeSpan.FromMilliseconds(100)),
TimeSpan.FromSeconds(3));
deadLetters.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
}
/// <summary>
/// When <c>HandleSubscribeAsync</c> throws (e.g. the driver's <c>SubscribeAsync</c> faults),
/// it replies <see cref="DriverInstanceActor.SubscriptionFailed"/> to the sender. On the
/// self-resubscribe path (<c>ResubscribeDesired</c> self-Tells <c>Subscribe</c>) the sender is
/// Self, so the failure reply lands back at the actor. Without a handler, it dead-letters.
/// This test verifies the symmetric swallow (added alongside the
/// <see cref="DriverInstanceActor.SubscriptionEstablished"/> one) prevents the dead-letter.
/// </summary>
[Fact]
public async Task Self_resubscribe_failure_does_not_deadletter_SubscriptionFailed()
{
// Subscribe to AllDeadLetters but ignore everything EXCEPT those carrying a
// SubscriptionFailed payload — keeps the probe mailbox precise.
var deadLetterProbe = CreateTestProbe();
deadLetterProbe.IgnoreMessages(
m => m is not AllDeadLetters { Message: DriverInstanceActor.SubscriptionFailed });
Sys.EventStream.Subscribe(deadLetterProbe.Ref, typeof(AllDeadLetters));
// Bring the actor to Connected state using a subscribable driver.
var driver = new SubscribableStubDriver();
var actor = Sys.ActorOf(DriverInstanceActor.Props(driver, reconnectInterval: TimeSpan.FromSeconds(30)));
actor.Tell(new DriverInstanceActor.InitializeRequested("{}"));
// Wait until Connected (subscribe path available).
AwaitCondition(() => driver.InitializeCount >= 1, TimeSpan.FromSeconds(2));
// Tell SubscriptionFailed directly — a faithful stand-in for the self-reply landing on the
// actor on the self-resubscribe path. This exercises exactly the Receive<SubscriptionFailed>
// handler (or proves its absence via a dead-letter).
actor.Tell(new DriverInstanceActor.SubscriptionFailed("boom"));
// Drive a round-trip to flush the actor mailbox before asserting.
// Subscribe Ask (which the Connected state can answer) as the barrier.
await actor.Ask<DriverInstanceActor.SubscriptionEstablished>(
new DriverInstanceActor.Subscribe(new[] { "barrier-ref" }, TimeSpan.FromMilliseconds(100)),
TimeSpan.FromSeconds(3));
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
/// (not via <see cref="StubDriver"/>) so the never-completing Init is reached through the
/// polymorphic <see cref="IDriver"/> call the actor makes.
/// </summary>
private sealed class BlockingInitDriver : IDriver, IWritable
{
/// <summary>Set true the moment InitializeAsync is entered.</summary>
public volatile bool InitializeStarted;
private readonly TaskCompletionSource _gate = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Gets the driver instance ID.</summary>
public string DriverInstanceId => "blocking-init-driver";
/// <summary>Gets the driver type.</summary>
public string DriverType => "Stub";
/// <summary>Never completes — keeps the actor in Connecting.</summary>
public Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
{
InitializeStarted = true;
return _gate.Task;
}
/// <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>Writes the specified requests (never reached — actor fast-fails in Connecting).</summary>
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
IReadOnlyList<WriteResult> results = writes.Select(_ => new WriteResult(0u)).ToList();
return Task.FromResult(results);
}
}
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";
}
}
}