5 Commits

6 changed files with 222 additions and 163 deletions
@@ -131,6 +131,11 @@ public final class MxGatewayCli implements Callable<Integer> {
}
static CommandLine commandLine(MxGatewayCliClientFactory clientFactory) {
return commandLine(clientFactory, new GrpcGalaxyClientFactory());
}
static CommandLine commandLine(
MxGatewayCliClientFactory clientFactory, GalaxyClientFactory galaxyClientFactory) {
CommandLine commandLine = new CommandLine(new MxGatewayCli(clientFactory));
commandLine.addSubcommand("version", new VersionCommand());
commandLine.addSubcommand("open-session", new OpenSessionCommand(clientFactory));
@@ -152,11 +157,11 @@ public final class MxGatewayCli implements Callable<Integer> {
commandLine.addSubcommand("stream-alarms", new StreamAlarmsCommand(clientFactory));
commandLine.addSubcommand("acknowledge-alarm", new AcknowledgeAlarmCommand(clientFactory));
commandLine.addSubcommand("smoke", new SmokeCommand(clientFactory));
commandLine.addSubcommand("galaxy-test-connection", new GalaxyTestConnectionCommand());
commandLine.addSubcommand("galaxy-last-deploy", new GalaxyDeployTimeCommand());
commandLine.addSubcommand("galaxy-discover", new GalaxyDiscoverCommand());
commandLine.addSubcommand("galaxy-browse", new GalaxyBrowseCommand());
commandLine.addSubcommand("galaxy-watch", new GalaxyWatchCommand());
commandLine.addSubcommand("galaxy-test-connection", new GalaxyTestConnectionCommand(galaxyClientFactory));
commandLine.addSubcommand("galaxy-last-deploy", new GalaxyDeployTimeCommand(galaxyClientFactory));
commandLine.addSubcommand("galaxy-discover", new GalaxyDiscoverCommand(galaxyClientFactory));
commandLine.addSubcommand("galaxy-browse", new GalaxyBrowseCommand(galaxyClientFactory));
commandLine.addSubcommand("galaxy-watch", new GalaxyWatchCommand(galaxyClientFactory));
commandLine.addSubcommand("batch", new BatchCommand(clientFactory));
return commandLine;
}
@@ -359,14 +364,20 @@ public final class MxGatewayCli implements Callable<Integer> {
}
abstract static class GalaxyCommand implements Callable<Integer> {
final GalaxyClientFactory galaxyClientFactory;
@Mixin
CommonOptions common = new CommonOptions();
@Option(names = "--json", description = "Write JSON output.")
boolean json;
GalaxyCommand(GalaxyClientFactory galaxyClientFactory) {
this.galaxyClientFactory = galaxyClientFactory;
}
GalaxyRepositoryClient connect() {
return GalaxyRepositoryClient.connect(common.resolved().toClientOptions());
return galaxyClientFactory.connect(common.resolved().toClientOptions());
}
}
@@ -375,6 +386,10 @@ public final class MxGatewayCli implements Callable<Integer> {
aliases = {"galaxy-test"},
description = "Calls GalaxyRepository.TestConnection.")
static final class GalaxyTestConnectionCommand extends GalaxyCommand {
GalaxyTestConnectionCommand(GalaxyClientFactory galaxyClientFactory) {
super(galaxyClientFactory);
}
@Override
public Integer call() {
try (GalaxyRepositoryClient client = connect()) {
@@ -399,6 +414,10 @@ public final class MxGatewayCli implements Callable<Integer> {
aliases = {"galaxy-deploy-time"},
description = "Calls GalaxyRepository.GetLastDeployTime.")
static final class GalaxyDeployTimeCommand extends GalaxyCommand {
GalaxyDeployTimeCommand(GalaxyClientFactory galaxyClientFactory) {
super(galaxyClientFactory);
}
@Override
public Integer call() {
try (GalaxyRepositoryClient client = connect()) {
@@ -423,6 +442,10 @@ public final class MxGatewayCli implements Callable<Integer> {
@Command(name = "galaxy-discover", description = "Calls GalaxyRepository.DiscoverHierarchy.")
static final class GalaxyDiscoverCommand extends GalaxyCommand {
GalaxyDiscoverCommand(GalaxyClientFactory galaxyClientFactory) {
super(galaxyClientFactory);
}
@Override
public Integer call() {
try (GalaxyRepositoryClient client = connect()) {
@@ -458,6 +481,10 @@ public final class MxGatewayCli implements Callable<Integer> {
name = "galaxy-browse",
description = "Browses the Galaxy hierarchy via GalaxyRepository.BrowseChildren.")
static final class GalaxyBrowseCommand extends GalaxyCommand {
GalaxyBrowseCommand(GalaxyClientFactory galaxyClientFactory) {
super(galaxyClientFactory);
}
@Spec
private CommandSpec spec;
@@ -718,6 +745,10 @@ public final class MxGatewayCli implements Callable<Integer> {
name = "galaxy-watch",
description = "Streams GalaxyRepository.WatchDeployEvents until cancelled.")
static final class GalaxyWatchCommand extends GalaxyCommand {
GalaxyWatchCommand(GalaxyClientFactory galaxyClientFactory) {
super(galaxyClientFactory);
}
@Option(
names = "--last-seen-deploy-time",
description =
@@ -1725,6 +1756,10 @@ public final class MxGatewayCli implements Callable<Integer> {
}
}
interface GalaxyClientFactory {
GalaxyRepositoryClient connect(MxGatewayClientOptions options);
}
interface MxGatewayCliClientFactory {
MxGatewayCliClient connect(CommonOptions options);
}
@@ -1781,6 +1816,13 @@ public final class MxGatewayCli implements Callable<Integer> {
MxEventStream streamEventsAfter(long afterWorkerSequence);
}
static final class GrpcGalaxyClientFactory implements GalaxyClientFactory {
@Override
public GalaxyRepositoryClient connect(MxGatewayClientOptions options) {
return GalaxyRepositoryClient.connect(options);
}
}
static final class GrpcMxGatewayCliClientFactory implements MxGatewayCliClientFactory {
@Override
public MxGatewayCliClient connect(CommonOptions options) {
@@ -5,8 +5,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.zb.mom.ww.mxgateway.client.MxGatewayAlarmFeedSubscription;
import com.zb.mom.ww.mxgateway.client.MxGatewayClient;
import com.zb.mom.ww.mxgateway.client.MxGatewayClientOptions;
import galaxy_repository.v1.GalaxyRepositoryOuterClass.DeployEvent;
import galaxy_repository.v1.GalaxyRepositoryOuterClass.GalaxyObject;
import io.grpc.stub.StreamObserver;
import java.io.ByteArrayInputStream;
@@ -749,6 +749,89 @@ final class MxGatewayCliTests {
}
}
// ---- galaxy-discover / galaxy-watch over the in-process harness (Task 6) ----
@Test
void galaxyDiscoverPrintsPagedHierarchyJson() {
// Drive the REAL GalaxyRepositoryClient.discoverHierarchy path over the
// in-process harness (Task 6), so the production galaxy-discover command
// exercises the real client paging loop against scripted objects instead
// of a hand-written seam. The harness's fake discoverHierarchy returns a
// single page carrying the scripted objects.
GalaxyObject area = GalaxyObject.newBuilder()
.setGobjectId(101)
.setTagName("Area001")
.setContainedName("Area001")
.setBrowseName("Area001")
.setIsArea(true)
.build();
GalaxyObject pump = GalaxyObject.newBuilder()
.setGobjectId(202)
.setTagName("Pump001")
.setContainedName("Pump001")
.setBrowseName("Pump001")
.setParentGobjectId(101)
.build();
try (InProcessGatewayHarness harness = new InProcessGatewayHarness()) {
harness.setScriptedObjects(List.of(area, pump));
CliRun run = executeGalaxy(new HarnessGalaxyClientFactory(harness), "galaxy-discover", "--json");
assertEquals(0, run.exitCode(), "errors:\n" + run.errors());
String out = run.output();
// galaxy-discover --json renders {"command":..,"options":..,"objects":[{galaxyObjectMap}]}.
assertTrue(out.contains("\"command\":\"galaxy-discover\""), out);
// Both scripted objects render with the flattened object fields.
assertTrue(out.contains("\"tagName\":\"Area001\""), out);
assertTrue(out.contains("\"tagName\":\"Pump001\""), out);
assertTrue(out.contains("\"gobjectId\":101"), out);
assertTrue(out.contains("\"gobjectId\":202"), out);
assertTrue(out.contains("\"parentGobjectId\":101"), out);
assertTrue(out.contains("\"isArea\":true"), out);
}
}
@Test
void galaxyWatchRendersScriptedDeployEvents() {
// Drive the REAL GalaxyRepositoryClient.watchDeployEvents / DeployEventStream
// path over the in-process harness. The harness's fake watchDeployEvents
// streams the scripted deploy events then completes; the CLI's --limit
// option caps how many it prints before closing the stream.
DeployEvent first = DeployEvent.newBuilder()
.setSequence(7L)
.setObjectCount(12)
.setAttributeCount(34)
.build();
DeployEvent second = DeployEvent.newBuilder()
.setSequence(8L)
.setObjectCount(13)
.setAttributeCount(35)
.build();
DeployEvent third = DeployEvent.newBuilder()
.setSequence(9L)
.setObjectCount(14)
.setAttributeCount(36)
.build();
try (InProcessGatewayHarness harness = new InProcessGatewayHarness()) {
harness.setScriptedDeployEvents(List.of(first, second, third));
// --limit 2 caps the feed at the first two scripted events.
CliRun run = executeGalaxy(
new HarnessGalaxyClientFactory(harness), "galaxy-watch", "--limit", "2", "--json");
assertEquals(0, run.exitCode(), "errors:\n" + run.errors());
String out = run.output();
// galaxy-watch --json prints one proto-JSON object per event; proto3
// JSON renders uint64 sequence as a decimal string.
assertTrue(out.contains("\"sequence\":\"7\""), out);
assertTrue(out.contains("\"objectCount\":12"), out);
assertTrue(out.contains("\"attributeCount\":34"), out);
assertTrue(out.contains("\"sequence\":\"8\""), out);
// --limit 2 must stop before printing the third scripted event.
assertFalse(out.contains("\"sequence\":\"9\""), out);
}
}
@Test
void batchCommandExecutesVersionAndEmitsEorMarker() {
CliRun run = executeBatch(new FakeClientFactory(), "version --json\n");
@@ -863,6 +946,24 @@ final class MxGatewayCliTests {
return new CliRun(exitCode, output.toString(), errors.toString());
}
/**
* Runs a galaxy subcommand against the supplied {@link
* MxGatewayCli.GalaxyClientFactory}, wiring it through the production
* {@code commandLine(gatewayFactory, galaxyFactory)} two-arg overload (Task 3
* seam). The gateway factory slot is unused by galaxy commands, so a plain
* {@link FakeClientFactory} fills it. Mirrors {@link #execute} for the
* gateway commands.
*/
private static CliRun executeGalaxy(MxGatewayCli.GalaxyClientFactory galaxyFactory, String... args) {
StringWriter output = new StringWriter();
StringWriter errors = new StringWriter();
picocli.CommandLine commandLine = MxGatewayCli.commandLine(new FakeClientFactory(), galaxyFactory);
commandLine.setOut(new PrintWriter(output, true));
commandLine.setErr(new PrintWriter(errors, true));
int exitCode = commandLine.execute(args);
return new CliRun(exitCode, output.toString(), errors.toString());
}
private record CliRun(int exitCode, String output, String errors) {
}
@@ -907,7 +1008,8 @@ final class MxGatewayCliTests {
/**
* Factory that wires the production {@link MxGatewayCli.GrpcMxGatewayCliClient}
* adapter around the harness's REAL {@link MxGatewayClient}, so the
* adapter around the harness's REAL
* {@link com.zb.mom.ww.mxgateway.client.MxGatewayClient}, so the
* stream-events command runs against the in-process scripted gateway over
* a real channel (exercising the real {@code MxEventStream}). Mirrors the
* production {@code GrpcMxGatewayCliClientFactory}, swapping only the
@@ -927,6 +1029,27 @@ final class MxGatewayCliTests {
}
}
/**
* Galaxy factory that returns the harness's REAL {@link
* com.zb.mom.ww.mxgateway.client.GalaxyRepositoryClient} over the in-process
* scripted {@code GalaxyRepository} service, so galaxy-discover / galaxy-watch
* exercise the real client (paging loop, deploy-event stream wrapper) against
* scripted payloads. Mirrors the production {@code GrpcGalaxyClientFactory},
* swapping only client construction for the harness-backed client.
*/
private static final class HarnessGalaxyClientFactory implements MxGatewayCli.GalaxyClientFactory {
private final InProcessGatewayHarness harness;
private HarnessGalaxyClientFactory(InProcessGatewayHarness harness) {
this.harness = harness;
}
@Override
public com.zb.mom.ww.mxgateway.client.GalaxyRepositoryClient connect(MxGatewayClientOptions options) {
return harness.galaxyClient();
}
}
private static final class OverflowingFakeClient implements MxGatewayCli.MxGatewayCliClient {
private final PrintWriter out;
@@ -7,6 +7,7 @@ using ZB.MOM.WW.MxGateway.Server.Metrics;
using ZB.MOM.WW.MxGateway.Server.Sessions;
using ZB.MOM.WW.MxGateway.Server.Workers;
using ZB.MOM.WW.MxGateway.Tests.Gateway.Workers.Fakes;
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Sessions;
@@ -330,62 +331,4 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncDisposable
DateTimeOffset.UtcNow);
}
/// <summary>
/// Fake worker process for testing process lifecycle. <see cref="WaitForExitAsync"/>
/// awaits a <see cref="TaskCompletionSource"/> completed only by
/// <see cref="Kill"/> or <see cref="MarkExited"/>, so a caller observing
/// completion can trust that exit actually happened — bringing this fake into
/// parity with the smoke-test variant in <c>GatewayEndToEndFakeWorkerSmokeTests</c>
/// (Tests-015 / Tests-023). This removes the latent regression vector where a
/// future <c>Assert.True(launcher.Process.HasExited)</c> in this file would
/// pass spuriously regardless of whether the worker truly exited.
/// </summary>
private sealed class FakeWorkerProcess(int processId) : IWorkerProcess
{
private readonly TaskCompletionSource _exited = new(TaskCreationOptions.RunContinuationsAsynchronously);
private bool _disposed;
/// <inheritdoc />
public int Id { get; } = processId;
/// <summary>Gets a value indicating whether the process has exited.</summary>
public bool HasExited { get; private set; }
/// <summary>Gets the process exit code, or null if the process has not exited.</summary>
public int? ExitCode { get; private set; }
/// <summary>Gets the number of times the Kill method was called.</summary>
public int KillCount { get; private set; }
/// <inheritdoc />
public ValueTask WaitForExitAsync(CancellationToken cancellationToken)
{
return new ValueTask(_exited.Task.WaitAsync(cancellationToken));
}
/// <inheritdoc />
public void Kill(bool entireProcessTree)
{
KillCount++;
MarkExited(-1);
}
/// <inheritdoc />
public void Dispose()
{
_disposed = true;
}
/// <summary>Gets a value indicating whether this process has been disposed.</summary>
public bool IsDisposed => _disposed;
/// <summary>Marks the process as exited with the specified exit code.</summary>
/// <param name="exitCode">The process exit code.</param>
public void MarkExited(int exitCode)
{
HasExited = true;
ExitCode = exitCode;
_exited.TrySetResult();
}
}
}
@@ -158,7 +158,7 @@ public sealed class WorkerClientTests
public async Task ReadLoop_WhenClientFaults_KillsOwnedWorkerProcess()
{
await using PipePair pipePair = await PipePair.CreateAsync();
FakeWorkerProcess process = new();
FakeWorkerProcess process = new(WorkerProcessId);
await using WorkerClient client = CreateClient(
pipePair,
new WorkerClientOptions
@@ -309,7 +309,7 @@ public sealed class WorkerClientTests
public async Task DisposeAsync_WhenOwnedWorkerStillRuns_KillsProcessBeforeDisposing()
{
await using PipePair pipePair = await PipePair.CreateAsync();
FakeWorkerProcess process = new();
FakeWorkerProcess process = new(WorkerProcessId);
WorkerClient client = CreateClient(pipePair, processHandle: CreateProcessHandle(process));
await client.DisposeAsync().AsTask().WaitAsync(TestTimeout);
@@ -764,49 +764,4 @@ public sealed class WorkerClientTests
}
}
private sealed class FakeWorkerProcess : IWorkerProcess
{
private readonly TaskCompletionSource _exited = new(TaskCreationOptions.RunContinuationsAsynchronously);
/// <summary>Gets the process ID.</summary>
public int Id { get; } = WorkerProcessId;
/// <summary>Gets a value indicating whether the process has exited.</summary>
public bool HasExited { get; private set; }
/// <summary>Gets the process exit code.</summary>
public int? ExitCode { get; private set; }
/// <summary>Gets the number of times kill was called.</summary>
public int KillCount { get; private set; }
/// <summary>Gets the last kill request's entire process tree flag.</summary>
public bool KillEntireProcessTree { get; private set; }
/// <summary>Gets a value indicating whether dispose was called.</summary>
public bool Disposed { get; private set; }
/// <inheritdoc />
public ValueTask WaitForExitAsync(CancellationToken cancellationToken)
{
return new ValueTask(_exited.Task.WaitAsync(cancellationToken));
}
/// <summary>Records a kill request.</summary>
/// <param name="entireProcessTree">Whether to kill the entire process tree.</param>
public void Kill(bool entireProcessTree)
{
KillCount++;
KillEntireProcessTree = entireProcessTree;
HasExited = true;
ExitCode = -1;
_exited.TrySetResult();
}
/// <inheritdoc />
public void Dispose()
{
Disposed = true;
}
}
}
@@ -4,6 +4,7 @@ using ZB.MOM.WW.MxGateway.Contracts;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Metrics;
using ZB.MOM.WW.MxGateway.Server.Workers;
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers;
@@ -68,6 +69,7 @@ public sealed class WorkerProcessLauncherTests
Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode);
Assert.True(process.KillCalled);
Assert.True(process.KillEntireProcessTree);
Assert.True(process.DisposeCalled);
Assert.True(pipeReservation.DisposeCalled);
Assert.Equal(1, metrics.GetSnapshot().WorkerKills);
@@ -121,6 +123,7 @@ public sealed class WorkerProcessLauncherTests
Assert.Equal(WorkerProcessLaunchErrorCode.StartupTimeout, exception.ErrorCode);
Assert.True(process.KillCalled);
Assert.True(process.KillEntireProcessTree);
Assert.True(process.DisposeCalled);
Assert.Equal(1, metrics.GetSnapshot().WorkerKills);
}
@@ -240,45 +243,6 @@ public sealed class WorkerProcessLauncherTests
}
}
/// <summary>Fake worker process for testing process lifecycle and exit behavior.</summary>
private sealed class FakeWorkerProcess(int processId) : IWorkerProcess
{
/// <inheritdoc />
public int Id { get; } = processId;
/// <summary>Gets or sets a value indicating whether the process has exited.</summary>
public bool HasExited { get; set; }
/// <summary>Gets or sets the process exit code.</summary>
public int? ExitCode { get; set; }
/// <summary>Gets a value indicating whether the Dispose method was called.</summary>
public bool DisposeCalled { get; private set; }
/// <summary>Gets a value indicating whether the Kill method was called.</summary>
public bool KillCalled { get; private set; }
/// <inheritdoc />
public ValueTask WaitForExitAsync(CancellationToken cancellationToken)
{
return ValueTask.CompletedTask;
}
/// <inheritdoc />
public void Kill(bool entireProcessTree)
{
Assert.True(entireProcessTree);
KillCalled = true;
HasExited = true;
}
/// <inheritdoc />
public void Dispose()
{
DisposeCalled = true;
}
}
/// <summary>Fake startup probe that immediately succeeds.</summary>
private sealed class SucceedingStartupProbe : IWorkerStartupProbe
{
@@ -4,10 +4,21 @@ namespace ZB.MOM.WW.MxGateway.Tests.TestSupport;
/// <summary>
/// Lightweight in-process stand-in for <see cref="IWorkerProcess"/> used by fake worker
/// launchers in end-to-end tests. Call <see cref="MarkExited"/> from the fake worker
/// body once the shutdown-ack handshake is complete so that callers awaiting
/// <see cref="WaitForExitAsync"/> observe real exit rather than a timeout.
/// launchers and lifecycle tests.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="WaitForExitAsync"/> awaits a <see cref="TaskCompletionSource"/> that is
/// completed only by <see cref="Kill"/> or <see cref="MarkExited"/>, so a caller observing
/// completion can trust that exit actually happened rather than passing spuriously.
/// </para>
/// <para>
/// The disposal and kill bookkeeping is exposed under several aliases
/// (<see cref="IsDisposed"/>/<see cref="DisposeCalled"/>/<see cref="Disposed"/>;
/// <see cref="KillCount"/>/<see cref="KillCalled"/>) so the various lifecycle tests can
/// keep their existing assertion vocabulary while sharing one definition.
/// </para>
/// </remarks>
public sealed class FakeWorkerProcess(int processId) : IWorkerProcess
{
private readonly TaskCompletionSource _exited = new(TaskCreationOptions.RunContinuationsAsynchronously);
@@ -15,23 +26,44 @@ public sealed class FakeWorkerProcess(int processId) : IWorkerProcess
/// <summary>Gets the process identifier.</summary>
public int Id { get; } = processId;
/// <summary>Gets a value indicating whether the process has exited.</summary>
public bool HasExited { get; private set; }
/// <summary>Gets or sets a value indicating whether the process has exited.</summary>
public bool HasExited { get; set; }
/// <summary>Gets the exit code of the process, or <see langword="null"/> if it has not exited.</summary>
public int? ExitCode { get; private set; }
/// <summary>Gets or sets the exit code of the process, or <see langword="null"/> if it has not exited.</summary>
public int? ExitCode { get; set; }
/// <summary>Gets the number of times <see cref="Kill"/> was called.</summary>
public int KillCount { get; private set; }
/// <summary>Gets a value indicating whether <see cref="Kill"/> was called at least once.</summary>
public bool KillCalled => KillCount > 0;
/// <summary>Gets the <c>entireProcessTree</c> flag from the most recent <see cref="Kill"/> call.</summary>
public bool KillEntireProcessTree { get; private set; }
/// <summary>Gets a value indicating whether <see cref="Dispose"/> was called.</summary>
public bool IsDisposed { get; private set; }
/// <summary>Gets a value indicating whether <see cref="Dispose"/> was called.</summary>
public bool DisposeCalled => IsDisposed;
/// <summary>Gets a value indicating whether <see cref="Dispose"/> was called.</summary>
public bool Disposed => IsDisposed;
/// <inheritdoc />
public ValueTask WaitForExitAsync(CancellationToken cancellationToken) =>
new(_exited.Task.WaitAsync(cancellationToken));
/// <inheritdoc />
public void Kill(bool entireProcessTree) => MarkExited(-1);
public void Kill(bool entireProcessTree)
{
KillCount++;
KillEntireProcessTree = entireProcessTree;
MarkExited(-1);
}
/// <inheritdoc />
public void Dispose()
{
}
public void Dispose() => IsDisposed = true;
/// <summary>
/// Marks the process as exited with the specified exit code and unblocks