Compare commits

...

12 Commits

Author SHA1 Message Date
Joseph Doherty a325ec54c7 docs(plan): record follow-ups batch execution outcome + live-verify results
v2-ci / build (push) Failing after 45s
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-19 02:45:23 -04:00
Joseph Doherty 85afb678cd docs(test): mark the audit builder-vs-wiring coverage boundary explicit
Code-review nit: Item C asserts BuildWriteFailureAuditEvent in isolation; the
single in-lock call-site wiring is covered by inspection + the production-proven
path (bb59fd4e). Documented as a deliberate boundary with a promote-if-second-
call-site note.
2026-06-19 02:22:41 -04:00
Joseph Doherty d8254630bb refactor(adminui): trim inline-script label + null-case test + helper-proxy note
Code-review nits: trim the seed name so the in-session dropdown label matches
the server-trimmed persisted name; add a null-selectedId test for
ResolveScriptLabel; and note in CreateNewScriptAsync that the ordering
invariant is proxied by the pure helper (AdminUI has no bUnit).
2026-06-19 02:16:59 -04:00
Joseph Doherty 36eb14e88d feat(opcua): emit Bad blip + AuditWriteUpdateEvent + sync fail-fast on failed device write 2026-06-19 02:14:58 -04:00
Joseph Doherty e047af0553 refactor(adminui): harden SetFullName (reject blank ref) + cover alarm-flag re-pick
Code-review nits: SetFullName now throws on a blank reference (was silently
persisting FullName:null → silent deploy-time bind failure), and a new test
covers the alarm-typed re-pick combo (SeedDefaultAlarm over an already-edited
alarm leaves it intact).
2026-06-19 02:08:43 -04:00
Joseph Doherty da57c307a7 fix(adminui): refresh script dropdown label after inline create
After inline "New script" creates an SC-… id, the entry is now added
to _scripts BEFORE _form.ScriptId is set so the <InputSelect> has a
matching <option> on first render and the displayed label is correct.
Extracts VirtualTagModalHelpers.ResolveScriptLabel as a testable pure
helper (5 new unit tests in VirtualTagScriptDropdownTests).
2026-06-19 02:06:51 -04:00
Joseph Doherty 2dd723e195 fix(adminui): preserve edited alarm fields on Galaxy address re-pick 2026-06-19 02:02:06 -04:00
Joseph Doherty f81fa76809 test(cli): assert Enable/Disable object node + add suffix-idempotency test
Closes the code-review gap: the Enable/Disable success tests now assert the
derived '.Condition' object node (the CallMethodObjectIds capture was added
but unused), and a new test proves an already-suffixed condition node isn't
double-suffixed (mirrors AcknowledgeAlarmAsync_LeavesConditionSuffixAlone).
2026-06-19 01:57:53 -04:00
Joseph Doherty eede0c926b test(opcuaclient): add AcknowledgeAsync stale-session race test + trim fallback delay
Closes the code-review coverage gap: AcknowledgeAsync now has its own
swap-across-the-gate regression test (CallAsync lands on the post-gate
session), the subscribe-path coverage gap is documented, and the bounded
fallback drops from 2s to 250ms (the buggy-path signal is a synchronous
pre-await read, so it always wins well inside the bound).
2026-06-19 01:56:56 -04:00
Joseph Doherty 6223bc970a refactor(adminui): tidy cert-audit review nits (fallthrough comment + single PkiStoreRoot read) 2026-06-19 01:51:38 -04:00
Joseph Doherty 88d5ba45bf feat(cli): add enable/disable condition commands (H4 client path) 2026-06-19 01:48:21 -04:00
Joseph Doherty eb328e5761 fix(opcuaclient): re-resolve session inside _gate in history/read paths (stale-session race) 2026-06-19 01:41:19 -04:00
24 changed files with 1393 additions and 84 deletions
@@ -1,16 +1,23 @@
{
"planPath": "docs/plans/2026-06-19-followups-batch.md",
"designPath": "docs/plans/2026-06-19-followups-batch-design.md",
"executionState": "PENDING",
"executionState": "COMPLETE",
"base": "master f57aa8fa",
"branchAtExecution": "feat/followups-batch",
"branchCreatedFrom": "master ad359c5c",
"outcome": {
"codeTasks": "T1-T6 all complete; 11 commits; full-solution build 0 errors; all touched suites green; per-task + final integration review READY TO MERGE",
"liveVerify": "T5 fully verified live (inline New script -> dropdown shows new script label). T4 substantially verified (picker opens, live gateway browse works, edited alarm+scale+isHistorized config commits); final Use-this-address pick-and-assert blocked by the Galaxy object browser's href=# name-links navigating away under browser automation (pre-existing picker quirk, unrelated to the SetFullName change; preservation covered by 6 unit tests).",
"findings": "T6 (B1) production already shipped bb59fd4e 2026-06-15 (like #400); delivered missing behavioural test coverage instead. Stray throwaway script SC-ff9c2a3a7044 'vtag-livecheck script' (blank, unbound) left in dev DB during T5 verify; Scripts page has no delete affordance.",
"reconsiderGates": "T7/T8 NOT built (awaiting explicit go-ahead). T9/T10 operator/rig verify. T11 hardware-blocked."
},
"tasks": [
{"id": 1, "ref": "A1", "subject": "OpcUaClient history session-capture-before-gate race fix", "classification": "standard", "status": "pending", "parallelizableWith": [2,3,4,5,6], "group": "A-actionable"},
{"id": 2, "ref": "A2", "subject": "Client.CLI enable/disable command (H4 client path)", "classification": "standard", "status": "pending", "parallelizableWith": [1,3,4,5,6], "group": "A-actionable"},
{"id": 3, "ref": "A3", "subject": "Cert-audit minor review nits (unreachable fallthrough comment + single PkiStoreRoot read)", "classification": "trivial", "status": "pending", "parallelizableWith": [1,2,4,5,6], "group": "A-actionable"},
{"id": 4, "ref": "B2", "subject": "AdminUI: preserve edited alarm fields on Galaxy address re-pick", "classification": "small", "status": "pending", "parallelizableWith": [1,2,3,5,6], "group": "B-deferred"},
{"id": 5, "ref": "B3", "subject": "AdminUI: refresh script dropdown label after inline create", "classification": "small", "status": "pending", "parallelizableWith": [1,2,3,4,6], "group": "B-deferred"},
{"id": 6, "ref": "B1", "subject": "Write-outcome residuals: Bad-quality blip + AuditWriteUpdateEvent + sync fail-fast", "classification": "standard", "status": "pending", "parallelizableWith": [1,2,3,4,5], "group": "B-deferred"},
{"id": 1, "ref": "A1", "subject": "OpcUaClient history session-capture-before-gate race fix", "classification": "standard", "status": "completed", "commits": ["eb328e57","eede0c92"], "parallelizableWith": [2,3,4,5,6], "group": "A-actionable"},
{"id": 2, "ref": "A2", "subject": "Client.CLI enable/disable command (H4 client path)", "classification": "standard", "status": "completed", "commits": ["88d5ba45","f81fa768"], "parallelizableWith": [1,3,4,5,6], "group": "A-actionable"},
{"id": 3, "ref": "A3", "subject": "Cert-audit minor review nits (unreachable fallthrough comment + single PkiStoreRoot read)", "classification": "trivial", "status": "completed", "commits": ["6223bc97"], "parallelizableWith": [1,2,4,5,6], "group": "A-actionable"},
{"id": 4, "ref": "B2", "subject": "AdminUI: preserve edited alarm fields on Galaxy address re-pick", "classification": "small", "status": "completed", "commits": ["2dd723e1","e047af05"], "liveVerify": "substantial (picker+gateway-browse+config-commit confirmed; final pick-and-assert blocked by object-browser href quirk; preservation unit-tested)", "parallelizableWith": [1,2,3,5,6], "group": "B-deferred"},
{"id": 5, "ref": "B3", "subject": "AdminUI: refresh script dropdown label after inline create", "classification": "small", "status": "completed", "commits": ["da57c307","d8254630"], "liveVerify": "PASS (inline New script -> dropdown label = new script)", "parallelizableWith": [1,2,3,4,6], "group": "B-deferred"},
{"id": 6, "ref": "B1", "subject": "Write-outcome residuals: Bad-quality blip + AuditWriteUpdateEvent + sync fail-fast", "classification": "standard", "status": "completed", "commits": ["36eb14e8","85afb678"], "note": "production already shipped bb59fd4e 2026-06-15; delivered missing behavioural test coverage + private->internal seam", "parallelizableWith": [1,2,3,4,5], "group": "B-deferred"},
{"id": 7, "ref": "B4", "subject": "F10b surgical DataType/IsArray in-place writes", "classification": "standard", "status": "pending", "gate": "RECONSIDER — previously decided against (dirty); do NOT build without explicit go-ahead", "group": "B-reconsider"},
{"id": 8, "ref": "B5", "subject": "Alarm-severity SetSeverity surgical update", "classification": "small", "status": "pending", "gate": "RECONSIDER — operationally invisible (alarm engine overwrites); do NOT build without explicit go-ahead", "group": "B-reconsider"},
{"id": 9, "ref": "C1", "subject": "Modbus-Int64 full live authoring on docker-dev", "classification": "verify", "status": "pending", "note": "operator/rig verify-only; seed a Modbus driver", "group": "C-verify"},
@@ -0,0 +1,55 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
[Command("disable", Description = "Disable an alarm condition (OPC UA Part 9 ConditionType Disable)")]
public class DisableCommand : CommandBase
{
/// <summary>
/// Creates the disable command used to disable an OPC UA alarm condition from the terminal.
/// </summary>
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
public DisableCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
/// <summary>
/// Gets the condition node ID of the alarm to disable.
/// </summary>
[CommandOption("node", 'n', Description = "Condition node ID of the alarm to disable", IsRequired = true)]
public string NodeId { get; init; } = default!;
/// <summary>
/// Connects to the server and disables the specified alarm condition.
/// </summary>
/// <param name="console">The CLI console used for output and cancellation handling.</param>
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var statusCode = await service.DisableAsync(NodeId, ct);
if (StatusCode.IsGood(statusCode))
await console.Output.WriteLineAsync($"Disable successful: {NodeId}");
else
await console.Output.WriteLineAsync($"Disable failed: {statusCode}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}
@@ -0,0 +1,55 @@
using CliFx.Attributes;
using CliFx.Infrastructure;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Client.Shared;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
[Command("enable", Description = "Enable an alarm condition (OPC UA Part 9 ConditionType Enable)")]
public class EnableCommand : CommandBase
{
/// <summary>
/// Creates the enable command used to enable an OPC UA alarm condition from the terminal.
/// </summary>
/// <param name="factory">The factory that creates the shared client service for the command run.</param>
public EnableCommand(IOpcUaClientServiceFactory factory) : base(factory)
{
}
/// <summary>
/// Gets the condition node ID of the alarm to enable.
/// </summary>
[CommandOption("node", 'n', Description = "Condition node ID of the alarm to enable", IsRequired = true)]
public string NodeId { get; init; } = default!;
/// <summary>
/// Connects to the server and enables the specified alarm condition.
/// </summary>
/// <param name="console">The CLI console used for output and cancellation handling.</param>
public override async ValueTask ExecuteAsync(IConsole console)
{
ConfigureLogging();
IOpcUaClientService? service = null;
try
{
var ct = console.RegisterCancellationHandler();
(service, _) = await CreateServiceAndConnectAsync(ct);
var statusCode = await service.EnableAsync(NodeId, ct);
if (StatusCode.IsGood(statusCode))
await console.Output.WriteLineAsync($"Enable successful: {NodeId}");
else
await console.Output.WriteLineAsync($"Enable failed: {statusCode}");
}
finally
{
if (service != null)
{
await service.DisconnectAsync();
service.Dispose();
}
}
}
}
@@ -135,6 +135,32 @@ public interface IOpcUaClientService : IDisposable
/// </returns>
Task<StatusCode> ShelveAlarmAsync(string conditionNodeId, ShelveKind kind, double shelvingTimeSeconds = 0, CancellationToken ct = default);
/// <summary>
/// Enables an alarm condition by invoking the OPC UA Part 9 ConditionType <c>Enable</c> method
/// (the H4 client-driven path). The method takes no input arguments.
/// </summary>
/// <param name="conditionNodeId">The condition node associated with the alarm being enabled.</param>
/// <param name="ct">The cancellation token that aborts the enable request.</param>
/// <returns>
/// <see cref="StatusCodes.Good"/> on success, or the server's bad <see cref="StatusCode"/>
/// (from the underlying <see cref="ServiceResultException"/>) when the enable call
/// returns a bad result. Other transport-level failures still surface as exceptions.
/// </returns>
Task<StatusCode> EnableAsync(string conditionNodeId, CancellationToken ct = default);
/// <summary>
/// Disables an alarm condition by invoking the OPC UA Part 9 ConditionType <c>Disable</c> method
/// (the H4 client-driven path). The method takes no input arguments.
/// </summary>
/// <param name="conditionNodeId">The condition node associated with the alarm being disabled.</param>
/// <param name="ct">The cancellation token that aborts the disable request.</param>
/// <returns>
/// <see cref="StatusCodes.Good"/> on success, or the server's bad <see cref="StatusCode"/>
/// (from the underlying <see cref="ServiceResultException"/>) when the disable call
/// returns a bad result. Other transport-level failures still surface as exceptions.
/// </returns>
Task<StatusCode> DisableAsync(string conditionNodeId, CancellationToken ct = default);
/// <summary>
/// Reads raw historical samples for a historized node.
/// </summary>
@@ -461,6 +461,50 @@ public sealed class OpcUaClientService : IOpcUaClientService
return StatusCodes.Good;
}
/// <inheritdoc />
public Task<StatusCode> EnableAsync(string conditionNodeId, CancellationToken ct = default) =>
CallEnableDisableAsync(conditionNodeId, enabling: true, ct);
/// <inheritdoc />
public Task<StatusCode> DisableAsync(string conditionNodeId, CancellationToken ct = default) =>
CallEnableDisableAsync(conditionNodeId, enabling: false, ct);
/// <summary>
/// Shared body for the H4 Enable/Disable client path. Invokes the OPC UA Part 9 ConditionType
/// <c>Enable</c>/<c>Disable</c> method (no input arguments) on the condition object node, mirroring
/// the <see cref="AcknowledgeAlarmAsync"/> convention: the methods live on the <c>.Condition</c>
/// child node, and a bad call result surfaces as the returned <see cref="StatusCode"/> rather than
/// escaping as an uncaught <see cref="ServiceResultException"/>.
/// </summary>
/// <param name="conditionNodeId">The condition node associated with the alarm.</param>
/// <param name="enabling"><c>true</c> to invoke Enable; <c>false</c> to invoke Disable.</param>
/// <param name="ct">The cancellation token that aborts the request.</param>
private async Task<StatusCode> CallEnableDisableAsync(string conditionNodeId, bool enabling, CancellationToken ct)
{
ThrowIfDisposed();
ThrowIfNotConnected();
// Enable/Disable live on the same .Condition child node as Acknowledge/Confirm.
var conditionObjId = conditionNodeId.EndsWith(".Condition")
? NodeId.Parse(conditionNodeId)
: NodeId.Parse(conditionNodeId + ".Condition");
var methodId = enabling ? MethodIds.ConditionType_Enable : MethodIds.ConditionType_Disable;
try
{
await _session!.CallMethodAsync(conditionObjId, methodId, [], ct);
}
catch (ServiceResultException ex)
{
Logger.Warning(ex, "Failed to {Operation} alarm on {ConditionId} (status {Status})",
enabling ? "enable" : "disable", conditionNodeId, ex.StatusCode);
return ex.StatusCode;
}
Logger.Debug("{Operation} alarm on {ConditionId}", enabling ? "Enabled" : "Disabled", conditionNodeId);
return StatusCodes.Good;
}
/// <inheritdoc />
public async Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)
@@ -82,6 +82,15 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
/// <summary>Per-connection gate. PRs 67+ serialize read/write/browse on this.</summary>
internal SemaphoreSlim Gate => _gate;
/// <summary>
/// Test-only seam to swap the active <see cref="Session"/> the way
/// <see cref="OnReconnectComplete"/> does at runtime, so the stale-session race the
/// read/history paths guard against (re-read Session inside <c>_gate</c>, not before)
/// can be exercised deterministically without standing up a live reconnect handler.
/// Production code never calls this — the SDK reconnect handler owns the real swap.
/// </summary>
internal void SetSessionForTest(ISession? session) => Session = session;
private DriverHealth _health = new(DriverState.Unknown, null, null);
private bool _disposed;
/// <summary>URL of the endpoint the driver actually connected to. Exposed via <see cref="HostName"/>.</summary>
@@ -1131,7 +1140,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
public async Task<ISubscriptionHandle> SubscribeAsync(
IReadOnlyList<string> fullReferences, TimeSpan publishingInterval, CancellationToken cancellationToken)
{
var session = RequireSession();
// Fast-fail before queuing if the driver isn't connected, but do NOT bind the
// subscription to this reference — a reconnect can swap Session while we wait on _gate.
// The session actually used is re-read inside the gate (Driver.OpcUaClient-001/-006).
_ = RequireSession();
var id = Interlocked.Increment(ref _nextSubscriptionId);
var handle = new OpcUaSubscriptionHandle(id);
@@ -1157,6 +1169,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Re-read Session inside the critical section: a reconnect completing while we were
// blocked on _gate has already swapped in the new session via OnReconnectComplete.
var session = Session
?? throw new InvalidOperationException(
"OpcUaClient session was lost before the subscription could be created.");
session.AddSubscription(subscription);
await subscription.CreateAsync(cancellationToken).ConfigureAwait(false);
@@ -1296,7 +1313,10 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
public async Task<IAlarmSubscriptionHandle> SubscribeAlarmsAsync(
IReadOnlyList<string> sourceNodeIds, CancellationToken cancellationToken)
{
var session = RequireSession();
// Fast-fail before queuing if the driver isn't connected, but do NOT bind the alarm
// subscription to this reference — a reconnect can swap Session while we wait on _gate.
// The session actually used is re-read inside the gate (Driver.OpcUaClient-001/-006).
_ = RequireSession();
var id = Interlocked.Increment(ref _nextAlarmSubscriptionId);
var handle = new OpcUaAlarmSubscriptionHandle(id);
@@ -1345,6 +1365,11 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Re-read Session inside the critical section: a reconnect completing while we were
// blocked on _gate has already swapped in the new session via OnReconnectComplete.
var session = Session
?? throw new InvalidOperationException(
"OpcUaClient session was lost before the alarm subscription could be created.");
session.AddSubscription(subscription);
await subscription.CreateAsync(cancellationToken).ConfigureAwait(false);
@@ -1410,31 +1435,42 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
// list without guarding the size themselves — e.g. a bulk-ack UI that built an empty
// list because the filter matched nothing.
if (acknowledgements.Count == 0) return;
var session = RequireSession();
// OPC UA A&C: call the AcknowledgeableConditionType.Acknowledge method on each
// condition node with EventId + Comment arguments. CallAsync accepts a batch —
// one CallMethodRequest per ack.
var callRequests = new CallMethodRequestCollection();
foreach (var ack in acknowledgements)
{
if (!TryParseNodeId(session, ack.ConditionId, out var conditionId)) continue;
callRequests.Add(new CallMethodRequest
{
ObjectId = conditionId,
MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [
new Variant(Array.Empty<byte>()), // EventId — server-side best-effort; empty resolves to 'most recent'
new Variant(new LocalizedText(ack.Comment ?? string.Empty)),
],
});
}
if (callRequests.Count == 0) return;
// Fast-fail before queuing if the driver isn't connected, but do NOT bind the ack calls
// (or the namespace-relative ConditionId parse) to this reference — a reconnect can swap
// Session while we wait on _gate. The session actually used is re-read inside the gate
// (Driver.OpcUaClient-001/-006).
_ = RequireSession();
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Re-read Session inside the critical section: a reconnect completing while we were
// blocked on _gate has already swapped in the new session via OnReconnectComplete.
// ConditionId parsing is namespace-relative, so it must use the current session's
// namespace table too.
var session = Session;
if (session is null) return;
// OPC UA A&C: call the AcknowledgeableConditionType.Acknowledge method on each
// condition node with EventId + Comment arguments. CallAsync accepts a batch —
// one CallMethodRequest per ack.
var callRequests = new CallMethodRequestCollection();
foreach (var ack in acknowledgements)
{
if (!TryParseNodeId(session, ack.ConditionId, out var conditionId)) continue;
callRequests.Add(new CallMethodRequest
{
ObjectId = conditionId,
MethodId = MethodIds.AcknowledgeableConditionType_Acknowledge,
InputArguments = [
new Variant(Array.Empty<byte>()), // EventId — server-side best-effort; empty resolves to 'most recent'
new Variant(new LocalizedText(ack.Comment ?? string.Empty)),
],
});
}
if (callRequests.Count == 0) return;
try
{
var resp = await session.CallAsync(
@@ -1615,20 +1651,30 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
private async Task<Core.Abstractions.HistoryReadResult> ExecuteHistoryReadAsync(
string fullReference, ExtensionObject historyReadDetails, CancellationToken ct)
{
var session = RequireSession();
if (!TryParseNodeId(session, fullReference, out var nodeId))
{
return new Core.Abstractions.HistoryReadResult([], null);
}
var nodesToRead = new HistoryReadValueIdCollection
{
new HistoryReadValueId { NodeId = nodeId },
};
// Make sure a session exists before queuing on the gate, but do NOT bind the wire call
// (or the namespace-relative NodeId parse) to this reference — a reconnect can swap
// Session while we wait on _gate. The session actually used is re-read inside the gate
// (Driver.OpcUaClient-001/-006).
_ = RequireSession();
await _gate.WaitAsync(ct).ConfigureAwait(false);
try
{
// Re-read Session inside the critical section: if a reconnect completed while we
// were blocked on _gate, OnReconnectComplete has already swapped in the new session.
// NodeId parsing is namespace-relative, so it must also use the current session's
// namespace table.
var session = Session;
if (session is null || !TryParseNodeId(session, fullReference, out var nodeId))
{
return new Core.Abstractions.HistoryReadResult([], null);
}
var nodesToRead = new HistoryReadValueIdCollection
{
new HistoryReadValueId { NodeId = nodeId },
};
var resp = await session.HistoryReadAsync(
requestHeader: null,
historyReadDetails: historyReadDetails,
@@ -1785,38 +1831,47 @@ public sealed class OpcUaClientDriver : IDriver, ITagDiscovery, IReadable, IWrit
string? sourceName, DateTime startUtc, DateTime endUtc, int maxEvents,
CancellationToken cancellationToken)
{
var session = RequireSession();
NodeId notifierNodeId;
if (string.IsNullOrEmpty(sourceName))
{
notifierNodeId = ObjectIds.Server;
}
else if (!TryParseNodeId(session, sourceName, out var parsed))
{
return new Core.Abstractions.HistoricalEventsResult([], null);
}
else
{
notifierNodeId = parsed;
}
var details = new ReadEventDetails
{
StartTime = startUtc,
EndTime = endUtc,
NumValuesPerNode = maxEvents <= 0 ? 0u : (uint)maxEvents,
Filter = BuildBaseEventFilter(),
};
var nodesToRead = new HistoryReadValueIdCollection
{
new HistoryReadValueId { NodeId = notifierNodeId },
};
// Confirm a session exists before queuing; the session actually used — and the
// namespace-relative source-NodeId parse — are re-read inside the gate so a reconnect
// mid-wait can't leave us reading from a closed session (Driver.OpcUaClient-001/-006).
_ = RequireSession();
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Re-read Session inside the critical section: OnReconnectComplete may have swapped
// in a new session while we were blocked on _gate, and the source-NodeId parse is
// namespace-relative so it must bind against the current session's namespace table.
var session = Session;
if (session is null) return new Core.Abstractions.HistoricalEventsResult([], null);
NodeId notifierNodeId;
if (string.IsNullOrEmpty(sourceName))
{
notifierNodeId = ObjectIds.Server;
}
else if (!TryParseNodeId(session, sourceName, out var parsed))
{
return new Core.Abstractions.HistoricalEventsResult([], null);
}
else
{
notifierNodeId = parsed;
}
var details = new ReadEventDetails
{
StartTime = startUtc,
EndTime = endUtc,
NumValuesPerNode = maxEvents <= 0 ? 0u : (uint)maxEvents,
Filter = BuildBaseEventFilter(),
};
var nodesToRead = new HistoryReadValueIdCollection
{
new HistoryReadValueId { NodeId = notifierNodeId },
};
var resp = await session.HistoryReadAsync(
requestHeader: null,
historyReadDetails: new ExtensionObject(details),
@@ -29,6 +29,13 @@ public sealed class CertificateStoreManager
private readonly string _pkiRoot;
private readonly IAuditWriter _audit;
/// <summary>
/// The resolved PKI store root directory (e.g. <c>pki</c>). Derived once from
/// <c>OpcUa:PkiStoreRoot</c> in the production ctor; callers should read this property
/// rather than re-resolving the config key independently.
/// </summary>
public string PkiRoot => _pkiRoot;
/// <summary>Production ctor — reads <c>OpcUa:PkiStoreRoot</c> (default <c>pki</c>).</summary>
/// <param name="config">App configuration.</param>
/// <param name="audit">The audit writer that persists Trust/Untrust/Delete actions to <c>ConfigAuditLog</c>.</param>
@@ -127,7 +127,7 @@ else
private void LoadAll()
{
DisposeRows();
var pkiRoot = Config.GetValue<string?>("OpcUa:PkiStoreRoot") ?? "pki";
var pkiRoot = CertManager.PkiRoot; // Single source: manager already resolved OpcUa:PkiStoreRoot (default "pki").
_rows = new()
{
LoadStore("Own", StoreKind.Own, Path.Combine(pkiRoot, "own", "certs")),
@@ -200,8 +200,14 @@ else
{
StoreKind.Trusted => CertManager.Delete("trusted", p.Thumbprint, actor),
StoreKind.Rejected => CertManager.Delete("rejected", p.Thumbprint, actor),
// Unreachable defensive guard — action buttons only render for Trusted/Rejected stores
// + the 3 literal verbs (Trust/Untrust/Delete); this arm never executes, so it
// intentionally does not route through CertificateStoreManager/audit.
_ => CertActionResult.Fail($"cannot delete from {p.Kind}"),
},
// Unreachable defensive guard — action buttons only render for Trusted/Rejected stores
// + the 3 literal verbs (Trust/Untrust/Delete); this arm never executes, so it
// intentionally does not route through CertificateStoreManager/audit.
_ => CertActionResult.Fail("unknown action"),
};
_statusError = !result.Success;
@@ -336,14 +336,12 @@
private void OnGalaxyAddressPicked(string address)
{
_galaxyAddress = address;
// A fresh {FullName} blob would drop any tag-level historize the operator already set on this
// edit; re-merge it so re-picking a Galaxy address never silently clears "Historize this tag".
var config = TagHistorizeConfig.Set(
JsonSerializer.Serialize(new { FullName = address }),
_historizeState.IsHistorized,
_historizeState.HistorianTagname);
// Re-merge any array intent for the same reason — a fresh {FullName} blob would otherwise drop it.
config = TagArrayConfig.Set(config, _arrayState.IsArray, _arrayState.ArrayLength);
// Re-picking a Galaxy address owns ONLY the address-derived FullName key — apply it over the EXISTING
// TagConfig so every other user-edited field survives verbatim. This preserves a hand-authored `alarm`
// object (FB-4: a re-pick must never clobber edited alarm fields) as well as the root history/array
// intent and any driver/unknown keys. TagConfigJson.SetFullName uses the same preserve-unknown idiom
// as the historize/array merge seams.
var config = TagConfigJson.SetFullName(_form.TagConfig, address);
_form.TagConfig = _galaxyPickedIsAlarm
? NativeAlarmModel.SeedDefaultAlarm(config)
: config;
@@ -321,7 +321,10 @@
_scriptCreateError = null;
try
{
var seedName = string.IsNullOrWhiteSpace(_form.Name) ? "New script" : $"{_form.Name} script";
// Trim so the local dropdown label matches what CreateScriptAsync persists (it Trim()s
// the name server-side) — otherwise stray whitespace makes the in-session label drift
// from every later modal open.
var seedName = string.IsNullOrWhiteSpace(_form.Name) ? "New script" : $"{_form.Name.Trim()} script";
var result = await Svc.CreateScriptAsync(seedName);
if (!result.Ok || string.IsNullOrEmpty(result.CreatedId))
{
@@ -329,14 +332,18 @@
return;
}
// Bind the new script and load its (blank) source so the inline editor renders + expands.
_form.ScriptId = result.CreatedId;
await LoadScriptSourceAsync();
// Make the freshly-created script a real option in the dropdown so the select stays coherent.
// Add the new script to the options list BEFORE setting the selected value so the
// <InputSelect> can resolve the label on first render — if we set ScriptId first the
// dropdown has no matching <option> yet and shows a blank/stale label. This ordering
// invariant is unit-tested via VirtualTagModalHelpers.ResolveScriptLabel (the AdminUI
// has no bUnit harness, so the pure helper proxies the render-cycle contract).
if (!_scripts.Any(s => s.Id == result.CreatedId))
{
_scripts.Add((result.CreatedId, $"{seedName} (CSharp)"));
}
// Bind the new script and load its (blank) source so the inline editor renders + expands.
_form.ScriptId = result.CreatedId;
await LoadScriptSourceAsync();
_scriptExpanded = true;
}
finally
@@ -0,0 +1,39 @@
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Uns;
/// <summary>
/// Pure helpers extracted from <see cref="VirtualTagModal"/> to support unit testing of state
/// logic that is otherwise embedded in Razor component lifecycle methods.
/// </summary>
internal static class VirtualTagModalHelpers
{
/// <summary>
/// Resolves the display label for the given <paramref name="selectedId"/> from the supplied
/// dropdown <paramref name="options"/> list.
/// </summary>
/// <param name="options">
/// The current in-memory options, each as an <c>(Id, Display)</c> pair. This list MUST include
/// the newly-created script entry BEFORE <c>selectedId</c> is set on the form; otherwise the
/// rendered <c>&lt;select&gt;</c> will have no matching <c>&lt;option&gt;</c> and show a blank
/// label.
/// </param>
/// <param name="selectedId">The id of the currently selected script (may be null or empty).</param>
/// <returns>
/// The display label for the selected id, or <c>null</c> when <paramref name="selectedId"/> is
/// empty or is not present in <paramref name="options"/>.
/// </returns>
internal static string? ResolveScriptLabel(
IEnumerable<(string Id, string Display)> options,
string? selectedId)
{
if (string.IsNullOrEmpty(selectedId))
return null;
foreach (var (id, display) in options)
{
if (id == selectedId)
return display;
}
return null;
}
}
@@ -43,4 +43,22 @@ public static class TagConfigJson
if (value is null) { o.Remove(name); return; }
o[name] = JsonValue.Create(value is Enum e ? e.ToString() : value);
}
/// <summary>
/// Merges a freshly-picked Galaxy reference (<c>tag_name.AttributeName</c>) into <paramref name="json"/>
/// by setting ONLY the canonical PascalCase <c>FullName</c> key — every other key is preserved verbatim.
/// This is the Galaxy address re-pick seam: re-picking an address must update the bound attribute WITHOUT
/// discarding fields the operator already edited independently of the address — ESPECIALLY a hand-authored
/// <c>alarm</c> object (and root history/array intent, scaling, etc.). Null/blank/malformed input starts
/// from a bare <c>{"FullName":...}</c> object.
/// </summary>
public static string SetFullName(string? json, string fullName)
{
// A blank reference is never a valid Galaxy bind — surface it loudly rather than persisting
// a poisoned "FullName": null/"" that would silently fail to bind at deploy time.
ArgumentException.ThrowIfNullOrWhiteSpace(fullName);
var o = ParseOrNew(json);
o["FullName"] = JsonValue.Create(fullName);
return Serialize(o);
}
}
@@ -1064,6 +1064,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
/// </list>
/// Silent value-wise — this node manager carries no logger; the gateway logs the underlying write failure
/// and the SDK trace captures any audit-report failure.
/// <para><c>internal</c> (not private) so the behavioural test drives the blip-then-settle continuation
/// against a booted node manager — see <c>NodeManagerWriteRevertTests</c>.</para>
/// </summary>
/// <param name="nodeId">The string id of the written variable node.</param>
/// <param name="outcome">The device-write outcome routed back by the gateway.</param>
@@ -1072,7 +1074,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
/// <param name="priorStatus">The node's real status captured before the optimistic write.</param>
/// <param name="clientUserId">The writing principal's user-id string (the identity's DisplayName), threaded
/// from <see cref="OnEquipmentTagWrite"/> to populate the audit event's ClientUserId; null when unknown.</param>
private void RevertOptimisticWriteIfNeeded(
internal void RevertOptimisticWriteIfNeeded(
string nodeId, NodeWriteOutcome outcome, object? optimisticValue, object? priorValue, StatusCode priorStatus,
string? clientUserId)
{
@@ -1132,7 +1134,10 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
/// <param name="priorValue">The node's real pre-write value (the audit OldValue).</param>
/// <param name="clientUserId">The writing principal's user-id string; null when unknown.</param>
/// <returns>A populated, unreported <see cref="AuditWriteUpdateEventState"/>.</returns>
private AuditWriteUpdateEventState BuildWriteFailureAuditEvent(
/// <remarks><c>internal</c> (not private) so <c>NodeManagerWriteRevertTests</c> can assert the populated
/// audit fields at the nearest deterministic seam (the end-to-end <c>Server.ReportEvent</c> dispatch would
/// need a subscribed event monitored-item to observe).</remarks>
internal AuditWriteUpdateEventState BuildWriteFailureAuditEvent(
BaseDataVariableState variable, NodeWriteOutcome outcome, object? optimisticValue, object? priorValue,
string? clientUserId)
{
@@ -0,0 +1,75 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Tests.Fakes;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests;
public class DisableCommandTests
{
/// <summary>Verifies that a successful disable prints a success message and targets the node.</summary>
[Fact]
public async Task Execute_Success_PrintsSuccessMessage()
{
var fakeService = new FakeOpcUaClientService
{
DisableResult = StatusCodes.Good
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new DisableCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyAlarm"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Disable successful");
fakeService.DisableCalls.Count.ShouldBe(1);
fakeService.DisableCalls[0].ShouldBe("ns=2;s=MyAlarm");
}
/// <summary>Verifies that a bad StatusCode from the service prints a failure message.</summary>
[Fact]
public async Task Execute_BadStatus_PrintsFailureMessage()
{
var fakeService = new FakeOpcUaClientService
{
DisableResult = StatusCodes.BadConditionAlreadyDisabled
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new DisableCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyAlarm"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Disable failed");
}
/// <summary>Verifies that the command disconnects and disposes in the finally block.</summary>
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new DisableCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyAlarm"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}
@@ -0,0 +1,75 @@
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Commands;
using ZB.MOM.WW.OtOpcUa.Client.CLI.Tests.Fakes;
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Tests;
public class EnableCommandTests
{
/// <summary>Verifies that a successful enable prints a success message and targets the node.</summary>
[Fact]
public async Task Execute_Success_PrintsSuccessMessage()
{
var fakeService = new FakeOpcUaClientService
{
EnableResult = StatusCodes.Good
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new EnableCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyAlarm"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Enable successful");
fakeService.EnableCalls.Count.ShouldBe(1);
fakeService.EnableCalls[0].ShouldBe("ns=2;s=MyAlarm");
}
/// <summary>Verifies that a bad StatusCode from the service prints a failure message.</summary>
[Fact]
public async Task Execute_BadStatus_PrintsFailureMessage()
{
var fakeService = new FakeOpcUaClientService
{
EnableResult = StatusCodes.BadConditionAlreadyEnabled
};
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new EnableCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyAlarm"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
var output = TestConsoleHelper.GetOutput(console);
output.ShouldContain("Enable failed");
}
/// <summary>Verifies that the command disconnects and disposes in the finally block.</summary>
[Fact]
public async Task Execute_DisconnectsInFinally()
{
var fakeService = new FakeOpcUaClientService();
var factory = new FakeOpcUaClientServiceFactory(fakeService);
var command = new EnableCommand(factory)
{
Url = "opc.tcp://localhost:4840",
NodeId = "ns=2;s=MyAlarm"
};
using var console = TestConsoleHelper.CreateConsole();
await command.ExecuteAsync(console);
fakeService.DisconnectCalled.ShouldBeTrue();
fakeService.DisposeCalled.ShouldBeTrue();
}
}
@@ -262,6 +262,32 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
return Task.FromResult(ShelveAlarmResult);
}
/// <summary>Gets the list of condition node IDs passed to EnableAsync calls.</summary>
public List<string> EnableCalls { get; } = [];
/// <summary>Gets or sets the status code returned by EnableAsync.</summary>
public StatusCode EnableResult { get; set; } = StatusCodes.Good;
/// <inheritdoc />
public Task<StatusCode> EnableAsync(string conditionNodeId, CancellationToken ct = default)
{
EnableCalls.Add(conditionNodeId);
return Task.FromResult(EnableResult);
}
/// <summary>Gets the list of condition node IDs passed to DisableAsync calls.</summary>
public List<string> DisableCalls { get; } = [];
/// <summary>Gets or sets the status code returned by DisableAsync.</summary>
public StatusCode DisableResult { get; set; } = StatusCodes.Good;
/// <inheritdoc />
public Task<StatusCode> DisableAsync(string conditionNodeId, CancellationToken ct = default)
{
DisableCalls.Add(conditionNodeId);
return Task.FromResult(DisableResult);
}
/// <inheritdoc />
public Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(
NodeId nodeId, DateTime startTime, DateTime endTime, int maxValues = 1000, CancellationToken ct = default)
@@ -208,11 +208,25 @@ internal sealed class FakeSessionAdapter : ISessionAdapter
/// </summary>
public List<object[]> CallMethodInputArgs { get; } = [];
/// <summary>
/// Records the object node id passed to each <see cref="CallMethodAsync"/> invocation,
/// so tests can assert which condition object a method was invoked on.
/// </summary>
public List<NodeId> CallMethodObjectIds { get; } = [];
/// <summary>
/// Records the method node id passed to each <see cref="CallMethodAsync"/> invocation,
/// so tests can assert the correct Part 9 method (e.g. Enable/Disable) was invoked.
/// </summary>
public List<NodeId> CallMethodMethodIds { get; } = [];
/// <inheritdoc />
public Task<IList<object>?> CallMethodAsync(NodeId objectId, NodeId methodId, object[] inputArguments,
CancellationToken ct = default)
{
CallMethodCount++;
CallMethodObjectIds.Add(objectId);
CallMethodMethodIds.Add(methodId);
CallMethodInputArgs.Add(inputArguments);
if (CallMethodException != null)
throw CallMethodException;
@@ -1174,6 +1174,110 @@ public class OpcUaClientServiceTests : IDisposable
result.Code.ShouldBe(StatusCodes.BadConditionAlreadyShelved);
}
// --- Enable / Disable tests (H4 client path) ---
/// <summary>
/// Verifies that EnableAsync invokes the ConditionType_Enable method with no input
/// arguments and returns <see cref="StatusCodes.Good"/> on success.
/// </summary>
[Fact]
public async Task EnableAsync_OnSuccess_CallsEnableMethodWithNoArgs()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.EnableAsync("ns=2;s=Cond");
result.ShouldBe(StatusCodes.Good);
session.CallMethodCount.ShouldBe(1);
session.CallMethodObjectIds[0].ShouldBe(NodeId.Parse("ns=2;s=Cond.Condition"));
session.CallMethodMethodIds[0].ShouldBe(MethodIds.ConditionType_Enable);
session.CallMethodInputArgs[0].ShouldBeEmpty();
}
/// <summary>
/// Verifies that DisableAsync invokes the ConditionType_Disable method with no input
/// arguments and returns <see cref="StatusCodes.Good"/> on success.
/// </summary>
[Fact]
public async Task DisableAsync_OnSuccess_CallsDisableMethodWithNoArgs()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.DisableAsync("ns=2;s=Cond");
result.ShouldBe(StatusCodes.Good);
session.CallMethodCount.ShouldBe(1);
session.CallMethodObjectIds[0].ShouldBe(NodeId.Parse("ns=2;s=Cond.Condition"));
session.CallMethodMethodIds[0].ShouldBe(MethodIds.ConditionType_Disable);
session.CallMethodInputArgs[0].ShouldBeEmpty();
}
/// <summary>
/// Verifies the ".Condition" suffix is appended when the caller supplies the source node,
/// but left alone when the caller already passes the condition node — mirrors
/// <see cref="AcknowledgeAlarmAsync_LeavesConditionSuffixAlone"/> for the Enable path so the
/// object-node derivation in CallEnableDisableAsync is regression-covered.
/// </summary>
[Fact]
public async Task EnableAsync_WhenConditionSuffixAlreadyPresent_DoesNotDoubleSuffix()
{
var session = new FakeSessionAdapter();
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.EnableAsync("ns=2;s=Cond.Condition");
result.ShouldBe(StatusCodes.Good);
session.CallMethodCount.ShouldBe(1);
session.CallMethodObjectIds[0].ShouldBe(NodeId.Parse("ns=2;s=Cond.Condition"));
}
/// <summary>
/// Verifies that a <see cref="ServiceResultException"/> from the session is captured and
/// returned as a bad <see cref="StatusCode"/> rather than propagating to the caller.
/// </summary>
[Fact]
public async Task EnableAsync_OnServiceResultException_ReturnsBadStatusCode()
{
var session = new FakeSessionAdapter
{
CallMethodException = new ServiceResultException(
StatusCodes.BadConditionAlreadyEnabled, "already enabled")
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.EnableAsync("ns=2;s=Cond");
StatusCode.IsBad(result).ShouldBeTrue();
result.Code.ShouldBe(StatusCodes.BadConditionAlreadyEnabled);
}
/// <summary>
/// Verifies that a <see cref="ServiceResultException"/> from the session is captured and
/// returned as a bad <see cref="StatusCode"/> rather than propagating to the caller.
/// </summary>
[Fact]
public async Task DisableAsync_OnServiceResultException_ReturnsBadStatusCode()
{
var session = new FakeSessionAdapter
{
CallMethodException = new ServiceResultException(
StatusCodes.BadConditionAlreadyDisabled, "already disabled")
};
_sessionFactory.EnqueueSession(session);
await _service.ConnectAsync(ValidSettings());
var result = await _service.DisableAsync("ns=2;s=Cond");
StatusCode.IsBad(result).ShouldBeTrue();
result.Code.ShouldBe(StatusCodes.BadConditionAlreadyDisabled);
}
// --- Alarm fallback path (Client.Shared-011) ---
/// <summary>
@@ -301,6 +301,42 @@ public sealed class FakeOpcUaClientService : IOpcUaClientService
return Task.FromResult(ShelveResult);
}
/// <summary>Gets or sets the status code returned by enable operations in UI tests.</summary>
public StatusCode EnableResult { get; set; } = StatusCodes.Good;
/// <summary>Gets or sets the exception thrown to simulate alarm enable failures in the UI.</summary>
public Exception? EnableException { get; set; }
/// <summary>Gets the number of times EnableAsync has been called.</summary>
public int EnableCallCount { get; private set; }
/// <summary>Gets the conditionNodeId of the last EnableAsync call.</summary>
public string? LastEnableCall { get; private set; }
/// <inheritdoc />
public Task<StatusCode> EnableAsync(string conditionNodeId, CancellationToken ct = default)
{
EnableCallCount++;
LastEnableCall = conditionNodeId;
if (EnableException != null) throw EnableException;
return Task.FromResult(EnableResult);
}
/// <summary>Gets or sets the status code returned by disable operations in UI tests.</summary>
public StatusCode DisableResult { get; set; } = StatusCodes.Good;
/// <summary>Gets or sets the exception thrown to simulate alarm disable failures in the UI.</summary>
public Exception? DisableException { get; set; }
/// <summary>Gets the number of times DisableAsync has been called.</summary>
public int DisableCallCount { get; private set; }
/// <summary>Gets the conditionNodeId of the last DisableAsync call.</summary>
public string? LastDisableCall { get; private set; }
/// <inheritdoc />
public Task<StatusCode> DisableAsync(string conditionNodeId, CancellationToken ct = default)
{
DisableCallCount++;
LastDisableCall = conditionNodeId;
if (DisableException != null) throw DisableException;
return Task.FromResult(DisableResult);
}
/// <inheritdoc />
public Task<IReadOnlyList<DataValue>> HistoryReadRawAsync(NodeId nodeId, DateTime startTime, DateTime endTime,
int maxValues = 1000, CancellationToken ct = default)
@@ -0,0 +1,221 @@
using Moq;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
/// <summary>
/// Regression coverage for the stale-session concurrency race in the history/read wire
/// paths. A background reconnect handler can swap <see cref="OpcUaClientDriver.Session"/>
/// while a caller is parked on <c>_gate.WaitAsync</c>. If a method captures the session
/// reference <i>before</i> the gate and uses it afterwards, it issues the wire call against
/// the closed/stale session. The correct idiom — already used by ReadAsync/WriteAsync — is
/// a fast-fail guard outside the gate plus an authoritative re-read of <c>Session</c>
/// <i>inside</i> the gate. These tests prove the history/read funnels follow it.
/// </summary>
/// <remarks>
/// The swap is staged so the race is exercised, not raced against:
/// <list type="number">
/// <item>The test acquires <c>_gate</c> first, so the method-under-test physically
/// cannot enter the critical section (read Session-in-gate / issue the wire call) until
/// the test releases the gate. Whatever the implementation does <i>after</i> the gate
/// therefore always sees the post-swap session.</item>
/// <item>The only thing that must be ordered is the <b>buggy</b> capture-before-gate:
/// its pre-gate NodeId parse reads the OLD session's <c>MessageContext</c>, which
/// completes a <see cref="TaskCompletionSource"/>. We wait on that signal so the swap
/// lands <i>after</i> the buggy capture has grabbed the OLD session — making the RED
/// outcome deterministic, not timing-dependent.</item>
/// <item>The fixed implementation reads no session member before the gate, so the
/// signal never fires; a bounded fallback then swaps+releases. That is correct for the
/// fixed path because its session read happens only after we release the gate, so the
/// swap is already visible regardless of ordering.</item>
/// </list>
/// A correct implementation re-reads <c>Session</c> inside the gate and lands the wire call
/// on the NEW session; the buggy capture-before-gate code lands it on the OLD one.
/// </remarks>
[Trait("Category", "Unit")]
public sealed class OpcUaClientStaleSessionRaceTests
{
private static Mock<ISession> NewSessionMock(TaskCompletionSource? prologueReached = null)
{
var resp = new HistoryReadResponse
{
ResponseHeader = new ResponseHeader(),
Results = new HistoryReadResultCollection(),
DiagnosticInfos = new DiagnosticInfoCollection(),
};
var mock = new Mock<ISession>(MockBehavior.Loose);
// NodeId parsing inside the driver resolves the reference against the session's
// MessageContext. This getter is read in the driver's synchronous prologue (before the
// gate), so signalling here proves the pre-gate capture path has run.
mock.SetupGet(s => s.MessageContext)
.Returns(new ServiceMessageContext())
.Callback(() => prologueReached?.TrySetResult());
mock.SetupGet(s => s.NamespaceUris).Returns(new NamespaceTable());
mock.Setup(s => s.HistoryReadAsync(
It.IsAny<RequestHeader>(),
It.IsAny<ExtensionObject>(),
It.IsAny<TimestampsToReturn>(),
It.IsAny<bool>(),
It.IsAny<HistoryReadValueIdCollection>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(resp);
// Acknowledge issues its wire call via CallAsync; stub it so AcknowledgeAsync can run to
// completion against whichever session it ends up binding to.
mock.Setup(s => s.CallAsync(
It.IsAny<RequestHeader>(),
It.IsAny<CallMethodRequestCollection>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(new CallResponse
{
ResponseHeader = new ResponseHeader(),
Results = new CallMethodResultCollection(),
DiagnosticInfos = new DiagnosticInfoCollection(),
});
return mock;
}
private static void VerifyWireHitNewSessionNotOld(Mock<ISession> newSession, Mock<ISession> oldSession)
{
newSession.Verify(s => s.HistoryReadAsync(
It.IsAny<RequestHeader>(), It.IsAny<ExtensionObject>(), It.IsAny<TimestampsToReturn>(),
It.IsAny<bool>(), It.IsAny<HistoryReadValueIdCollection>(), It.IsAny<CancellationToken>()),
Times.Once);
oldSession.Verify(s => s.HistoryReadAsync(
It.IsAny<RequestHeader>(), It.IsAny<ExtensionObject>(), It.IsAny<TimestampsToReturn>(),
It.IsAny<bool>(), It.IsAny<HistoryReadValueIdCollection>(), It.IsAny<CancellationToken>()),
Times.Never);
}
private static void VerifyAckWireHitNewSessionNotOld(Mock<ISession> newSession, Mock<ISession> oldSession)
{
newSession.Verify(s => s.CallAsync(
It.IsAny<RequestHeader>(), It.IsAny<CallMethodRequestCollection>(), It.IsAny<CancellationToken>()),
Times.Once);
oldSession.Verify(s => s.CallAsync(
It.IsAny<RequestHeader>(), It.IsAny<CallMethodRequestCollection>(), It.IsAny<CancellationToken>()),
Times.Never);
}
/// <summary>
/// ExecuteHistoryReadAsync (the ReadRaw/ReadProcessed/ReadAtTime funnel) must issue the
/// HistoryRead against the session current <i>after</i> the gate, not a reference
/// captured before WaitAsync.
/// </summary>
[Fact]
public async Task ReadRawAsync_uses_session_swapped_in_across_the_gate_not_the_captured_one()
{
var ct = TestContext.Current.CancellationToken;
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-stale-raw");
var prologueReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var oldSession = NewSessionMock(prologueReached);
var newSession = NewSessionMock();
drv.SetSessionForTest(oldSession.Object);
// Hold the gate so the method parks on WaitAsync after running its synchronous prologue.
await drv.Gate.WaitAsync(ct);
var call = drv.ReadRawAsync(
"ns=2;s=Counter", DateTime.UtcNow.AddMinutes(-5), DateTime.UtcNow, 1000, ct);
// Wait until the buggy capture-before-gate has grabbed the OLD session (signalled via
// its MessageContext read), then stage the reconnect swap and release the gate. The
// fixed path reads no pre-gate session member, so the signal never fires and the
// bounded fallback elapses — harmless, because the fixed read happens only after the
// gate is released and therefore always sees the swapped session.
await WaitForPreGateCaptureOrFallbackAsync(prologueReached.Task, ct);
drv.SetSessionForTest(newSession.Object);
drv.Gate.Release();
await call;
VerifyWireHitNewSessionNotOld(newSession, oldSession);
}
/// <summary>
/// ReadEventsAsync is a separate HistoryRead site with the same hazard — it must also
/// re-read Session inside the gate rather than use the pre-gate capture.
/// </summary>
[Fact]
public async Task ReadEventsAsync_uses_session_swapped_in_across_the_gate_not_the_captured_one()
{
var ct = TestContext.Current.CancellationToken;
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-stale-events");
var prologueReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// ReadEventsAsync only parses the source NodeId when sourceName is non-empty, so pass a
// concrete source id to force the prologue's MessageContext read (and its signal).
var oldSession = NewSessionMock(prologueReached);
var newSession = NewSessionMock();
drv.SetSessionForTest(oldSession.Object);
await drv.Gate.WaitAsync(ct);
var call = drv.ReadEventsAsync(
sourceName: "ns=2;s=Pump17", startUtc: DateTime.UtcNow.AddMinutes(-5),
endUtc: DateTime.UtcNow, maxEvents: 100, cancellationToken: ct);
await WaitForPreGateCaptureOrFallbackAsync(prologueReached.Task, ct);
drv.SetSessionForTest(newSession.Object);
drv.Gate.Release();
await call;
VerifyWireHitNewSessionNotOld(newSession, oldSession);
}
/// <summary>
/// AcknowledgeAsync issues its Acknowledge method <c>CallAsync</c> against the session
/// current after the gate — and parses the namespace-relative ConditionId against that
/// same session — rather than a reference captured before WaitAsync. This is the third
/// gate-protected wire site; the two subscribe paths (<c>SubscribeAsync</c>,
/// <c>SubscribeAlarmsAsync</c>) received the identical fix but are not covered here
/// because asserting them requires a live <c>Subscription</c> object (the SDK's
/// <c>AddSubscription</c>/<c>CreateAsync</c> can't be exercised through this mock seam);
/// their correctness is reviewable by inspection against this same idiom.
/// </summary>
[Fact]
public async Task AcknowledgeAsync_uses_session_swapped_in_across_the_gate_not_the_captured_one()
{
var ct = TestContext.Current.CancellationToken;
using var drv = new OpcUaClientDriver(new OpcUaClientDriverOptions(), "opcua-stale-ack");
var prologueReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var oldSession = NewSessionMock(prologueReached);
var newSession = NewSessionMock();
drv.SetSessionForTest(oldSession.Object);
await drv.Gate.WaitAsync(ct);
var call = drv.AcknowledgeAsync(
[new AlarmAcknowledgeRequest("ns=2;s=Pump17", "ns=2;s=Pump17", "operator ack")], ct);
await WaitForPreGateCaptureOrFallbackAsync(prologueReached.Task, ct);
drv.SetSessionForTest(newSession.Object);
drv.Gate.Release();
await call;
VerifyAckWireHitNewSessionNotOld(newSession, oldSession);
}
/// <summary>
/// Awaits the buggy path's pre-gate-capture signal, or a bounded fallback when it never
/// fires (the fixed path performs no pre-gate session member read). The buggy-path signal
/// fires from a synchronous <c>MessageContext</c> read that runs before any await, so it
/// always wins the race well inside the fallback — keeping the RED outcome deterministic.
/// The fallback only matters for the GREEN (fixed) path where swap ordering is irrelevant
/// (the fixed read happens only after the gate is released), so a short bound keeps the
/// suite fast without weakening the guarantee.
/// </summary>
private static async Task WaitForPreGateCaptureOrFallbackAsync(Task signal, CancellationToken ct)
{
var fallback = Task.Delay(TimeSpan.FromMilliseconds(250), ct);
await Task.WhenAny(signal, fallback);
}
}
@@ -12,6 +12,7 @@
<ItemGroup>
<PackageReference Include="xunit.v3"/>
<PackageReference Include="Shouldly"/>
<PackageReference Include="Moq"/>
<PackageReference Include="Microsoft.NET.Test.Sdk"/>
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
@@ -0,0 +1,109 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns.TagEditors;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// Unit tests for <see cref="TagConfigJson.SetFullName"/> — the pure merge helper the TagModal's Galaxy
/// address-picked handler uses to apply a freshly-picked <c>tag_name.AttributeName</c> reference. Re-picking
/// a Galaxy address must update ONLY the address-derived <c>FullName</c> key and carry every other
/// user-edited field over verbatim — ESPECIALLY a manually-authored <c>alarm</c> object (FB-4 / B2). The
/// previous handler rebuilt the config from a bare <c>{"FullName":...}</c> blob, silently dropping the alarm.
/// </summary>
public sealed class GalaxyAddressRepickMergeTests
{
[Fact]
public void Repick_preserves_an_already_edited_alarm_object()
{
// The operator authored an alarm, then re-picks the bound attribute to fix a typo.
const string current =
"""{"FullName":"Pump_001.OldAttr","alarm":{"alarmType":"LimitAlarm","severity":250,"historizeToAveva":false}}""";
var merged = TagConfigJson.SetFullName(current, "Pump_001.NewAttr");
// The new address is applied...
var fullName = ReadFullName(merged);
fullName.ShouldBe("Pump_001.NewAttr");
// ...and the hand-edited alarm survives the re-pick intact.
var alarm = NativeAlarmModel.FromJson(merged);
alarm.IsAlarm.ShouldBeTrue();
alarm.AlarmType.ShouldBe("LimitAlarm");
alarm.Severity.ShouldBe(250);
alarm.HistorizeToAveva.ShouldBe(false);
}
[Fact]
public void Repick_with_no_alarm_just_sets_the_address()
{
var merged = TagConfigJson.SetFullName("""{"FullName":"Pump_001.OldAttr"}""", "Pump_001.NewAttr");
ReadFullName(merged).ShouldBe("Pump_001.NewAttr");
NativeAlarmModel.FromJson(merged).IsAlarm.ShouldBeFalse();
}
[Fact]
public void Repick_preserves_other_user_edited_non_address_fields()
{
// History intent + an array shape + an arbitrary scaling key the operator set independently of the
// address — all must survive a re-pick that only owns FullName.
const string current =
"""{"FullName":"Pump_001.OldAttr","isHistorized":true,"historianTagname":"Line3_Temp","isArray":true,"arrayLength":8,"scale":0.1}""";
var merged = TagConfigJson.SetFullName(current, "Pump_001.NewAttr");
ReadFullName(merged).ShouldBe("Pump_001.NewAttr");
var hist = TagHistorizeConfig.Read(merged);
hist.IsHistorized.ShouldBeTrue();
hist.HistorianTagname.ShouldBe("Line3_Temp");
var arr = TagArrayConfig.Read(merged);
arr.IsArray.ShouldBeTrue();
arr.ArrayLength.ShouldBe(8u);
merged.ShouldContain("\"scale\":0.1");
}
[Fact]
public void Set_on_empty_or_malformed_input_starts_from_a_bare_FullName_object()
{
var merged = TagConfigJson.SetFullName("not json", "Pump_001.NewAttr");
ReadFullName(merged).ShouldBe("Pump_001.NewAttr");
merged.ShouldStartWith("{");
merged.ShouldEndWith("}");
}
[Fact]
public void Repick_with_alarm_flag_does_not_overwrite_existing_alarm_object()
{
// Mirrors the handler's alarm-typed re-pick: SeedDefaultAlarm(SetFullName(existing, addr)).
// The operator authored an alarm, then re-picks an alarm-typed Galaxy attribute — the
// SeedDefaultAlarm no-op guard must leave the edited alarm intact, not re-seed a default.
const string current =
"""{"FullName":"Pump_001.OldAttr","alarm":{"alarmType":"LimitAlarm","severity":250,"historizeToAveva":false}}""";
var merged = NativeAlarmModel.SeedDefaultAlarm(TagConfigJson.SetFullName(current, "Pump_001.NewAttr"));
ReadFullName(merged).ShouldBe("Pump_001.NewAttr");
var alarm = NativeAlarmModel.FromJson(merged);
alarm.IsAlarm.ShouldBeTrue();
alarm.AlarmType.ShouldBe("LimitAlarm");
alarm.Severity.ShouldBe(250);
alarm.HistorizeToAveva.ShouldBe(false);
}
[Fact]
public void SetFullName_rejects_a_blank_reference()
{
Should.Throw<ArgumentException>(() => TagConfigJson.SetFullName("""{"FullName":"x"}""", " "));
}
// Mirror of TagModal.ReadFullName — extracts FullName from a Galaxy TagConfig blob.
private static string ReadFullName(string json)
{
using var doc = System.Text.Json.JsonDocument.Parse(json);
return doc.RootElement.TryGetProperty("FullName", out var fn) ? fn.GetString() ?? "" : "";
}
}
@@ -0,0 +1,99 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Uns;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// Unit tests for <see cref="VirtualTagModalHelpers.ResolveScriptLabel"/> — the pure helper that
/// resolves a script's display label from the in-memory options list. The bug scenario: after an
/// inline "New script" create, the dropdown label drifted because the new entry was appended to the
/// options list AFTER the selected value was set, so the rendered select had no matching option.
/// The fix is to add the entry first, then set the selected value; this helper captures that
/// invariant.
/// </summary>
[Trait("Category", "Unit")]
public sealed class VirtualTagScriptDropdownTests
{
// --- ResolveScriptLabel ---
[Fact]
public void ResolveScriptLabel_ReturnsNull_WhenOptionsDoNotContainId()
{
// Represents the bug scenario: options list does NOT yet include the newly-created id.
var options = new List<(string Id, string Display)>
{
("SC-existing001", "OldScript (CSharp)"),
};
var label = VirtualTagModalHelpers.ResolveScriptLabel(options, "SC-newscript00");
label.ShouldBeNull();
}
[Fact]
public void ResolveScriptLabel_ReturnsDisplay_WhenOptionsContainId()
{
// Represents the fixed scenario: the new entry is in the options before label is resolved.
var options = new List<(string Id, string Display)>
{
("SC-existing001", "OldScript (CSharp)"),
("SC-newscript00", "MyTag script (CSharp)"),
};
var label = VirtualTagModalHelpers.ResolveScriptLabel(options, "SC-newscript00");
label.ShouldBe("MyTag script (CSharp)");
}
[Fact]
public void ResolveScriptLabel_ReturnsNull_WhenSelectedIdIsEmpty()
{
var options = new List<(string Id, string Display)>
{
("SC-existing001", "OldScript (CSharp)"),
};
var label = VirtualTagModalHelpers.ResolveScriptLabel(options, "");
label.ShouldBeNull();
}
[Fact]
public void ResolveScriptLabel_ReturnsNull_WhenSelectedIdIsNull()
{
// The helper parameter is string? — a null selection resolves to no label, not a throw.
var options = new List<(string Id, string Display)>
{
("SC-existing001", "OldScript (CSharp)"),
};
var label = VirtualTagModalHelpers.ResolveScriptLabel(options, null);
label.ShouldBeNull();
}
[Fact]
public void ResolveScriptLabel_ReturnsNull_WhenOptionsIsEmpty()
{
var label = VirtualTagModalHelpers.ResolveScriptLabel(
Array.Empty<(string Id, string Display)>(), "SC-newscript00");
label.ShouldBeNull();
}
[Fact]
public void ResolveScriptLabel_ReturnsCorrectLabel_WhenMultipleOptionsExist()
{
var options = new List<(string Id, string Display)>
{
("SC-aaa", "Alpha (CSharp)"),
("SC-bbb", "Beta (CSharp)"),
("SC-ccc", "Gamma (CSharp)"),
};
VirtualTagModalHelpers.ResolveScriptLabel(options, "SC-aaa").ShouldBe("Alpha (CSharp)");
VirtualTagModalHelpers.ResolveScriptLabel(options, "SC-bbb").ShouldBe("Beta (CSharp)");
VirtualTagModalHelpers.ResolveScriptLabel(options, "SC-ccc").ShouldBe("Gamma (CSharp)");
}
}
@@ -0,0 +1,227 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// Write-outcome self-correction — the BEHAVIOURAL half of the failed-device-write surfacing
/// (the pure decision tables live in <see cref="EquipmentWriteGateTests"/>). Boots a real
/// <see cref="OtOpcUaSdkServer"/> through <see cref="OpcUaApplicationHost"/> (the same harness
/// <see cref="NodeManagerHistorizeTests"/> uses) so the continuation runs against a live node
/// manager (real <c>Lock</c> + <c>SystemContext</c> + <c>Server</c>), and drives
/// <see cref="OtOpcUaNodeManager.RevertOptimisticWriteIfNeeded"/> +
/// <see cref="OtOpcUaNodeManager.BuildWriteFailureAuditEvent"/> directly:
/// <list type="bullet">
/// <item>Item B (Bad-quality blip + settle): a FAILED outcome on a node still holding the
/// optimistic value settles the node back to its prior value/status; SUCCESS / a moved-on poll
/// leave the node untouched.</item>
/// <item>Item C (AuditWriteUpdateEvent): the built audit event-state carries SourceNode=node,
/// AttributeId=Value, OldValue=prior, NewValue=attempted, ClientUserId=writer, Status=false, and
/// the device Reason in its Message. (The end-to-end <c>Server.ReportEvent</c> dispatch needs a
/// subscribed event monitored-item to observe — the nearest deterministic seam is the builder.)</item>
/// </list>
/// <para>
/// Coverage boundary (deliberate): Item C asserts the audit-event <i>builder</i> in isolation,
/// not its single call-site wiring inside <see cref="OtOpcUaNodeManager.RevertOptimisticWriteIfNeeded"/>
/// (line ~1107). Observing that wiring end-to-end would require a subscribed event monitored-item;
/// the one in-lock builder call is covered by inspection + the production-proven path (shipped
/// <c>bb59fd4e</c>). If a second audit call-site is ever added, promote this to an observed-event test.
/// </para>
/// </summary>
public sealed class NodeManagerWriteRevertTests : IDisposable
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(
Path.GetTempPath(),
$"otopcua-write-revert-{Guid.NewGuid():N}");
// ───────────────────────────── Item B — Bad-quality blip + settle ─────────────────────────────
/// <summary>(B1) A FAILED device-write outcome on a node that still holds the optimistic value SETTLES the
/// node back to its captured prior value + prior status (the transient Bad blip coalesces within one
/// publishing interval — see the method remarks — so we assert the observable settled state).</summary>
[Fact]
public async Task Failed_outcome_settles_node_back_to_prior_value_and_status()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true);
// Prior state = Good 7; the SDK then optimistically applied 42 (the write the device will reject).
nm.WriteValue("eq-1/sp", 7, OpcUaQuality.Good, DateTime.UtcNow);
var node = nm.TryGetVariable("eq-1/sp")!;
node.Value = 42; // simulate the SDK's optimistic apply of the rejected write
nm.RevertOptimisticWriteIfNeeded(
"eq-1/sp",
outcome: new NodeWriteOutcome(false, "device rejected register 42"),
optimisticValue: 42,
priorValue: 7,
priorStatus: StatusCodes.Good,
clientUserId: "op");
node.Value.ShouldBe(7); // settled back to prior value
node.StatusCode.ShouldBe((StatusCode)StatusCodes.Good); // settled back to prior status (NOT stuck Bad)
await host.DisposeAsync();
}
/// <summary>(B2) A SUCCESS outcome NEVER reverts — the optimistic value stands (the next poll re-confirms
/// it via the normal WriteValue path).</summary>
[Fact]
public async Task Successful_outcome_leaves_optimistic_value()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true);
nm.WriteValue("eq-1/sp", 7, OpcUaQuality.Good, DateTime.UtcNow);
var node = nm.TryGetVariable("eq-1/sp")!;
node.Value = 42;
nm.RevertOptimisticWriteIfNeeded(
"eq-1/sp",
outcome: new NodeWriteOutcome(true, null),
optimisticValue: 42, priorValue: 7, priorStatus: StatusCodes.Good, clientUserId: "op");
node.Value.ShouldBe(42); // success ⇒ optimistic value stands
await host.DisposeAsync();
}
/// <summary>(B3) A failed outcome where a fresh driver poll already moved the node OFF the optimistic value
/// does NOT clobber the poll — the node keeps the fresh polled value (the still-holds-optimistic guard).</summary>
[Fact]
public async Task Failed_outcome_does_not_clobber_a_fresh_poll()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true);
nm.WriteValue("eq-1/sp", 7, OpcUaQuality.Good, DateTime.UtcNow);
var node = nm.TryGetVariable("eq-1/sp")!;
node.Value = 99; // a fresh poll already republished the confirmed register value (NOT the optimistic 42)
nm.RevertOptimisticWriteIfNeeded(
"eq-1/sp",
outcome: new NodeWriteOutcome(false, "device rejected"),
optimisticValue: 42, priorValue: 7, priorStatus: StatusCodes.Good, clientUserId: "op");
node.Value.ShouldBe(99); // poll value preserved — not reverted to 7
await host.DisposeAsync();
}
/// <summary>(B4) An unknown node id (rebuilt/removed in the interim) is a no-op — the continuation must not
/// throw out of its fire-and-forget body.</summary>
[Fact]
public async Task Failed_outcome_on_missing_node_is_a_noop()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
Should.NotThrow(() => nm.RevertOptimisticWriteIfNeeded(
"eq-1/gone",
outcome: new NodeWriteOutcome(false, "device rejected"),
optimisticValue: 42, priorValue: 7, priorStatus: StatusCodes.Good, clientUserId: "op"));
await host.DisposeAsync();
}
// ───────────────────────────── Item C — AuditWriteUpdateEvent builder ─────────────────────────────
/// <summary>(C1) The built audit event reflects the rejected write: SourceNode = the node, AttributeId =
/// Value, OldValue = prior, NewValue = attempted, ClientUserId = the writer, the AuditEvent Status boolean
/// = false (failed), and the device Reason is carried in the Message.</summary>
[Fact]
public async Task Built_audit_event_reflects_the_failed_write()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true);
nm.WriteValue("eq-1/sp", 7, OpcUaQuality.Good, DateTime.UtcNow);
var node = nm.TryGetVariable("eq-1/sp")!;
var audit = nm.BuildWriteFailureAuditEvent(
node,
outcome: new NodeWriteOutcome(false, "FC06 rejected"),
optimisticValue: 42,
priorValue: 7,
clientUserId: "op");
audit.ShouldNotBeNull();
audit.SourceNode.Value.ShouldBe(node.NodeId);
audit.AttributeId.Value.ShouldBe((uint)Attributes.Value);
audit.OldValue.Value.ShouldBe(7);
audit.NewValue.Value.ShouldBe(42);
audit.ClientUserId.Value.ShouldBe("op");
audit.Status.Value.ShouldBeFalse(); // AuditEvent Status = false ⇒ the write failed
audit.Message.Value.Text.ShouldContain("FC06 rejected"); // device Reason carried in the Message
await host.DisposeAsync();
}
/// <summary>(C2) When the device gives no Reason, the audit Message still carries a sensible default
/// ("device write rejected") rather than an empty/null message.</summary>
[Fact]
public async Task Built_audit_event_uses_default_reason_when_none_supplied()
{
var (host, server) = await BootAsync();
var nm = server.NodeManager!;
nm.EnsureVariable("eq-1/sp", parentFolderNodeId: null, displayName: "Sp", dataType: "Int32", writable: true);
nm.WriteValue("eq-1/sp", 7, OpcUaQuality.Good, DateTime.UtcNow);
var node = nm.TryGetVariable("eq-1/sp")!;
var audit = nm.BuildWriteFailureAuditEvent(
node,
outcome: new NodeWriteOutcome(false, null),
optimisticValue: 42, priorValue: 7, clientUserId: "op");
audit.Message.Value.Text.ShouldContain("device write rejected");
await host.DisposeAsync();
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var host = new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.WriteRevertTest",
ApplicationUri = $"urn:OtOpcUa.WriteRevertTest:{Guid.NewGuid():N}",
OpcUaPort = AllocateFreePort(),
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance);
var server = new OtOpcUaSdkServer();
await host.StartAsync(server, Ct);
return (host, server);
}
private static int AllocateFreePort()
{
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>Cleans up the PKI root directory.</summary>
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch { /* best-effort cleanup */ }
}
}
}