Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Grpc/NodeCommandGrpcServiceTests.cs
T
Joseph Doherty 09aaabbeef fix(alarms): AdminUI /alerts ack/shelve reports the scripted engine's verdict (#950)
The /alerts buttons went central->node fire-and-forget and always showed
"Ack sent". AdminOperationsActor now spawns a per-request
AlarmCommandVerdictCollector (7 s window, under the client's 10 s ask) that
sends the command with AlarmCommand.VerdictRequested and gathers each node's
answer, finishing early once every node it sent to has answered.

- gRPC plane: CentralCommunicationActor tells the collector the dialled
  ClusterNode set and one verdict per node. A node handles a
  verdict_requested AlarmCommandMessage by asking its driver host
  (ScriptedAlarmHostActor.ExecuteAlarmCommand, the #937 path, no ask deadline,
  bounded 5 s) and returns it in the ADDITIVE ExecuteAck.alarm_verdict.
  Transport failure / timeout / empty ack (pre-#950 node) => that node unknown.
- DPS: published with the collector as sender; each ScriptedAlarmHostActor
  answers (non-owners NotOwned); expected set = Up driver members.
- Aggregation: any owner applied => Applied (partial noted); else any
  unknown/silent node => Outcome unknown (never "refused"); else owner
  refusal => Refused: <reason>; else no owner => Not applied.
- UI: green Applied / red Refused (reason) / amber Outcome unknown, per-node
  detail in the details pane; a verdict-less reply (validation, server fault,
  pre-#950 singleton) renders as before.

Wire is back-compatible both ways (new proto fields only; VerdictRequested and
NotOwned default false). Real-wire test through the real router, dialer,
interceptor and NodeCommandGrpcService (red without the node change).

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-01 19:45:17 -05:00

277 lines
13 KiB
C#

using Akka.Hosting;
using Akka.TestKit.Xunit;
using Grpc.Core;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Mesh;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Protos.MeshTransport.V1;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Host.Grpc;
using ZB.MOM.WW.OtOpcUa.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.Grpc;
/// <summary>
/// Verifies the node-side command ingress (mesh gRPC command plane, Phase 1): each of the four
/// central→node commands is decoded off its <see cref="CommandEnvelope"/> and handed to the
/// registered <c>NodeCommunicationActor</c> as the same CLR record every other transport
/// delivers, an undecodable envelope is refused with <see cref="StatusCode.InvalidArgument"/>, and
/// a call landing in the boot window before the actor is registered is refused with
/// <see cref="StatusCode.Unavailable"/>.
/// </summary>
/// <remarks>
/// The actor is a <c>TestProbe</c> registered under <see cref="NodeCommunicationActorKey"/>: what
/// this service owes the rest of the system is the exact message the real actor already knows how to
/// re-emit, so asserting on what arrives at the registry key is the whole contract. The onward leg —
/// comm actor to EventStream to the real driver host — is pinned unchanged by
/// <c>EventStreamCommandDeliveryTests</c> in the Runtime test project.
/// </remarks>
public sealed class NodeCommandGrpcServiceTests : TestKit
{
private static readonly CorrelationId AlarmCorrelation = new(Guid.NewGuid());
private static ServerCallContext Ctx() => new FakeServerCallContext();
private static NodeCommandGrpcService NewService(ActorRegistry registry) =>
new(registry, NullLogger<NodeCommandGrpcService>.Instance);
[Fact]
public async Task Each_of_the_four_commands_reaches_the_comm_actor_as_its_domain_record()
{
var probe = CreateTestProbe();
var registry = new ActorRegistry();
registry.Register<NodeCommunicationActorKey>(probe.Ref);
var service = NewService(registry);
var dispatch = new DispatchDeployment(
new DeploymentId(Guid.NewGuid()), new RevisionHash("rev-1"), new CorrelationId(Guid.NewGuid()));
var restart = new RestartDriver("cluster-a", "drv-1", "alice", Guid.NewGuid());
var reconnect = new ReconnectDriver("cluster-a", "drv-2", "bob", Guid.NewGuid());
var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", "looked at it", null);
(await service.Execute(MeshTransportDtoMapper.ToEnvelope(dispatch), Ctx())).ShouldNotBeNull();
probe.ExpectMsg<DispatchDeployment>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(dispatch);
await service.Execute(MeshTransportDtoMapper.ToEnvelope(restart), Ctx());
probe.ExpectMsg<RestartDriver>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(restart);
await service.Execute(MeshTransportDtoMapper.ToEnvelope(reconnect), Ctx());
probe.ExpectMsg<ReconnectDriver>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(reconnect);
await service.Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx());
probe.ExpectMsg<AlarmCommand>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(alarm);
}
/// <summary>
/// #950: an alarm command asking for a verdict goes to the driver host as an <c>ExecuteAlarmCommand</c> (no ask
/// deadline — nothing else carries it here), NOT to the comm actor, and the host's answer rides the ack.
/// </summary>
[Fact]
public async Task A_verdict_request_asks_the_driver_host_and_returns_its_answer()
{
var comm = CreateTestProbe();
var driverHost = CreateTestProbe();
driverHost.SetAutoPilot(new Akka.TestKit.DelegateAutoPilot((sender, msg) =>
{
if (msg is ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmHostActor.ExecuteAlarmCommand ask)
{
sender.Tell(new AlarmCommandOutcome(ask.Command.AlarmId, ask.Command.Operation,
AlarmCommandVerdict.NotApplied, "last load failed"), Akka.Actor.ActorRefs.NoSender);
}
return Akka.TestKit.AutoPilot.KeepRunning;
}));
var registry = new ActorRegistry();
registry.Register<NodeCommunicationActorKey>(comm.Ref);
registry.Register<DriverHostActorKey>(driverHost.Ref);
var service = NewService(registry);
var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null, VerdictRequested: true);
var ack = await service.Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx());
var asked = driverHost.ExpectMsg<ZB.MOM.WW.OtOpcUa.Runtime.ScriptedAlarms.ScriptedAlarmHostActor.ExecuteAlarmCommand>(
cancellationToken: TestContext.Current.CancellationToken);
asked.Command.AlarmId.ShouldBe("alarm-7");
asked.DeadlineUtc.ShouldBeNull();
ack.AlarmVerdict.ShouldNotBeNull();
var outcome = MeshTransportDtoMapper.FromProto(ack.AlarmVerdict, "alarm-7", "Acknowledge");
outcome.Verdict.ShouldBe(AlarmCommandVerdict.NotApplied);
outcome.Reason.ShouldBe("last load failed");
comm.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
}
/// <summary>#950: an engine that does not answer in time is an unknown (timed-out) verdict, never a failed call.</summary>
[Fact]
public async Task A_silent_driver_host_is_a_timed_out_unknown()
{
var registry = new ActorRegistry();
registry.Register<NodeCommunicationActorKey>(CreateTestProbe().Ref);
registry.Register<DriverHostActorKey>(CreateTestProbe().Ref);
var service = new NodeCommandGrpcService(registry, NullLogger<NodeCommandGrpcService>.Instance)
{
VerdictWait = TimeSpan.FromMilliseconds(300),
};
var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null, VerdictRequested: true);
var ack = await service.Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx());
ack.AlarmVerdict.Verdict.ShouldBe(AlarmVerdict.OutcomeUnknown);
ack.AlarmVerdict.TimedOut.ShouldBeTrue();
}
/// <summary>#950: a node with no driver host owns no scripted alarm — answered NotApplied/NotOwned.</summary>
[Fact]
public async Task A_verdict_request_on_a_node_without_a_driver_host_is_not_owned()
{
var registry = new ActorRegistry();
registry.Register<NodeCommunicationActorKey>(CreateTestProbe().Ref);
var service = NewService(registry);
var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null, VerdictRequested: true);
var ack = await service.Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx());
ack.AlarmVerdict.Verdict.ShouldBe(AlarmVerdict.NotApplied);
ack.AlarmVerdict.NotOwned.ShouldBeTrue();
}
/// <summary>#950: without the request (a pre-#950 central) the one-way path is untouched — an empty ack.</summary>
[Fact]
public async Task An_alarm_command_without_a_verdict_request_stays_one_way()
{
var comm = CreateTestProbe();
var driverHost = CreateTestProbe();
var registry = new ActorRegistry();
registry.Register<NodeCommunicationActorKey>(comm.Ref);
registry.Register<DriverHostActorKey>(driverHost.Ref);
var alarm = new AlarmCommand("alarm-7", "Acknowledge", "carol", null, null);
var ack = await NewService(registry).Execute(MeshTransportDtoMapper.ToEnvelope(alarm, AlarmCorrelation), Ctx());
ack.AlarmVerdict.ShouldBeNull();
comm.ExpectMsg<AlarmCommand>(cancellationToken: TestContext.Current.CancellationToken).ShouldBe(alarm);
driverHost.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
}
[Fact]
public async Task A_call_in_the_boot_window_before_the_actor_is_registered_is_unavailable()
{
// Nothing registered: the ActorSystem exists but AddOtOpcUaRuntime has not spawned the comm
// actor yet. Unavailable (not Internal) because the condition is transient and retryable —
// central's dialer may try the same node again a moment later and succeed.
var service = NewService(new ActorRegistry());
var dispatch = new DispatchDeployment(
new DeploymentId(Guid.NewGuid()), new RevisionHash("rev-1"), new CorrelationId(Guid.NewGuid()));
var ex = await Should.ThrowAsync<RpcException>(
() => service.Execute(MeshTransportDtoMapper.ToEnvelope(dispatch), Ctx()));
ex.StatusCode.ShouldBe(StatusCode.Unavailable);
}
[Fact]
public async Task An_unset_oneof_is_invalid_argument()
{
var probe = CreateTestProbe();
var registry = new ActorRegistry();
registry.Register<NodeCommunicationActorKey>(probe.Ref);
var service = NewService(registry);
var ex = await Should.ThrowAsync<RpcException>(() => service.Execute(
new CommandEnvelope { CorrelationId = Guid.NewGuid().ToString("N") }, Ctx()));
ex.StatusCode.ShouldBe(StatusCode.InvalidArgument);
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
}
[Theory]
[MemberData(nameof(UndecodableEnvelopes))]
public async Task An_envelope_whose_fields_do_not_parse_is_invalid_argument(CommandEnvelope envelope)
{
var probe = CreateTestProbe();
var registry = new ActorRegistry();
registry.Register<NodeCommunicationActorKey>(probe.Ref);
var service = NewService(registry);
var ex = await Should.ThrowAsync<RpcException>(() => service.Execute(envelope, Ctx()));
ex.StatusCode.ShouldBe(StatusCode.InvalidArgument);
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(200), TestContext.Current.CancellationToken);
}
public static TheoryData<CommandEnvelope> UndecodableEnvelopes() =>
[
// Deployment id is not a hyphenless GUID -> FormatException out of the mapper.
new CommandEnvelope
{
CorrelationId = Guid.NewGuid().ToString("N"),
DispatchDeployment = new DispatchDeploymentCommand
{
DeploymentId = "not-a-guid",
RevisionHash = "rev-1",
CorrelationId = Guid.NewGuid().ToString("N"),
},
},
// Revision hash is blank -> ArgumentException out of RevisionHash.Parse.
new CommandEnvelope
{
CorrelationId = Guid.NewGuid().ToString("N"),
DispatchDeployment = new DispatchDeploymentCommand
{
DeploymentId = Guid.NewGuid().ToString("N"),
RevisionHash = "",
CorrelationId = Guid.NewGuid().ToString("N"),
},
},
// Restart command with an unparseable correlation id -> FormatException.
new CommandEnvelope
{
CorrelationId = Guid.NewGuid().ToString("N"),
RestartDriver = new RestartDriverCommand
{
ClusterId = "cluster-a",
DriverInstanceId = "drv-1",
ActorByUserName = "alice",
CorrelationId = "nope",
},
},
];
[Fact]
public async Task An_undecodable_envelope_in_the_boot_window_is_invalid_argument_not_unavailable()
{
// Ordering pin: decode runs BEFORE the registry lookup. Unavailable invites the caller to
// retry, and an envelope this build cannot decode will never decode — reporting it as a
// readiness problem would turn a permanent fault into an unbounded retry loop.
var service = NewService(new ActorRegistry());
var ex = await Should.ThrowAsync<RpcException>(() => service.Execute(
new CommandEnvelope { CorrelationId = Guid.NewGuid().ToString("N") }, Ctx()));
ex.StatusCode.ShouldBe(StatusCode.InvalidArgument);
}
/// <summary>Minimal <see cref="ServerCallContext"/>; this RPC reads nothing off the context but its method name.</summary>
private sealed class FakeServerCallContext : ServerCallContext
{
protected override string MethodCore => "/mesh_transport.v1.NodeCommandService/Execute";
protected override string HostCore => "localhost";
protected override string PeerCore => "ipv4:127.0.0.1:0";
protected override DateTime DeadlineCore => DateTime.MaxValue;
protected override Metadata RequestHeadersCore => [];
protected override CancellationToken CancellationTokenCore => CancellationToken.None;
protected override Metadata ResponseTrailersCore { get; } = [];
protected override Status StatusCore { get; set; }
protected override WriteOptions? WriteOptionsCore { get; set; }
protected override AuthContext AuthContextCore => new(null, new Dictionary<string, List<AuthProperty>>());
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) =>
throw new NotSupportedException();
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => Task.CompletedTask;
}
}