Compare commits
15 Commits
82755a3623
...
8df5ab381a
| Author | SHA1 | Date | |
|---|---|---|---|
| 8df5ab381a | |||
| 6f21d926d7 | |||
| aa8ae6613b | |||
| 44d676aede | |||
| e2b1a6686a | |||
| 01bdb484de | |||
| 3bb4d5a082 | |||
| 4ab3bd55e5 | |||
| 70d2842c16 | |||
| 4966ef3359 | |||
| 0efa7d8cca | |||
| ea17528767 | |||
| 1cfad83c06 | |||
| 76ffd5c9a3 | |||
| 6030bfa18e |
@@ -85,6 +85,8 @@ powershell -ExecutionPolicy Bypass -File scripts/run-client-e2e-tests.ps1
|
||||
|
||||
When source code changes, build and test the affected component before reporting work done. If the change crosses component boundaries, build each affected component — don't rely on a single top-level build:
|
||||
|
||||
**Run targeted tests per task, never the full suite each time.** When executing a plan task-by-task, run only the tests that exercise the code that task touched (`dotnet test --filter "FullyQualifiedName~<TestClass>"`, or the per-task test named in the plan). The full gateway suite is slow and leaves orphaned testhost processes — run it at most once per phase (after a related batch of tasks lands), not after every task.
|
||||
|
||||
| Changed area | Required verification |
|
||||
|---|---|
|
||||
| Contracts or `.proto` files | regenerate generated code, then build gateway, worker, and every generated client touched by the contract |
|
||||
|
||||
@@ -6,6 +6,9 @@ dependencies {
|
||||
implementation project(':zb-mom-ww-mxgateway-client')
|
||||
implementation "com.google.protobuf:protobuf-java-util:${protobufVersion}"
|
||||
implementation "info.picocli:picocli:${picocliVersion}"
|
||||
|
||||
testImplementation "io.grpc:grpc-inprocess:${grpcVersion}"
|
||||
testImplementation "io.grpc:grpc-testing:${grpcVersion}"
|
||||
}
|
||||
|
||||
application {
|
||||
|
||||
+48
-6
@@ -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) {
|
||||
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package com.zb.mom.ww.mxgateway.cli;
|
||||
|
||||
import com.zb.mom.ww.mxgateway.client.GalaxyRepositoryClient;
|
||||
import com.zb.mom.ww.mxgateway.client.MxGatewayClient;
|
||||
import com.zb.mom.ww.mxgateway.client.MxGatewayClientOptions;
|
||||
import galaxy_repository.v1.GalaxyRepositoryGrpc;
|
||||
import galaxy_repository.v1.GalaxyRepositoryOuterClass.DeployEvent;
|
||||
import galaxy_repository.v1.GalaxyRepositoryOuterClass.DiscoverHierarchyReply;
|
||||
import galaxy_repository.v1.GalaxyRepositoryOuterClass.DiscoverHierarchyRequest;
|
||||
import galaxy_repository.v1.GalaxyRepositoryOuterClass.GalaxyObject;
|
||||
import galaxy_repository.v1.GalaxyRepositoryOuterClass.WatchDeployEventsRequest;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.inprocess.InProcessChannelBuilder;
|
||||
import io.grpc.inprocess.InProcessServerBuilder;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import mxaccess_gateway.v1.MxAccessGatewayGrpc;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.CloseSessionReply;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.CloseSessionRequest;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.MxEvent;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.ProtocolStatus;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.ProtocolStatusCode;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.SessionState;
|
||||
|
||||
/**
|
||||
* Test fixture that stands up an in-process gRPC server hosting scripted fake
|
||||
* {@code MxAccessGateway} and {@code GalaxyRepository} service implementations,
|
||||
* so the real Java client types ({@link MxGatewayClient} /
|
||||
* {@link GalaxyRepositoryClient}) can be driven over a real channel.
|
||||
*
|
||||
* <p>The real streaming wrappers ({@code MxEventStream} /
|
||||
* {@code DeployEventStream}) have package-private constructors and
|
||||
* {@link GalaxyRepositoryClient} is {@code final}, so the streaming and galaxy
|
||||
* CLI commands cannot be exercised through the lightweight {@code FakeSession}
|
||||
* seam. Driving the real client over an in-process channel against scripted
|
||||
* services is the clean alternative; Tasks 5 and 6 add the CLI assertions on
|
||||
* top of this fixture.
|
||||
*
|
||||
* <p>Scripted payloads are settable via constructor args or setters. Each
|
||||
* instance uses a unique server name so harnesses do not collide. The
|
||||
* {@code directExecutor()} wiring keeps all dispatch on the calling thread, so
|
||||
* no background threads are leaked.
|
||||
*/
|
||||
final class InProcessGatewayHarness implements AutoCloseable {
|
||||
private final String serverName;
|
||||
private final Server server;
|
||||
private final ManagedChannel channel;
|
||||
private final FakeGatewayService fakeGateway;
|
||||
private final FakeGalaxyService fakeGalaxy;
|
||||
|
||||
/** Starts a harness with empty scripted payloads; populate via setters. */
|
||||
InProcessGatewayHarness() {
|
||||
this(List.of(), List.of(), List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a harness with the supplied scripted payloads.
|
||||
*
|
||||
* @param scriptedEvents events {@code streamEvents} pushes before completing
|
||||
* @param scriptedObjects objects {@code discoverHierarchy} returns (single page)
|
||||
* @param scriptedDeployEvents events {@code watchDeployEvents} streams before completing
|
||||
*/
|
||||
InProcessGatewayHarness(
|
||||
List<MxEvent> scriptedEvents,
|
||||
List<GalaxyObject> scriptedObjects,
|
||||
List<DeployEvent> scriptedDeployEvents) {
|
||||
this.serverName = "mxgw-cli-harness-" + UUID.randomUUID();
|
||||
this.fakeGateway = new FakeGatewayService(scriptedEvents);
|
||||
this.fakeGalaxy = new FakeGalaxyService(scriptedObjects, scriptedDeployEvents);
|
||||
try {
|
||||
this.server = InProcessServerBuilder.forName(serverName)
|
||||
.directExecutor()
|
||||
.addService(fakeGateway)
|
||||
.addService(fakeGalaxy)
|
||||
.build()
|
||||
.start();
|
||||
} catch (IOException error) {
|
||||
throw new IllegalStateException("failed to start in-process gateway harness", error);
|
||||
}
|
||||
this.channel = InProcessChannelBuilder.forName(serverName).directExecutor().build();
|
||||
}
|
||||
|
||||
/** Replaces the scripted {@code streamEvents} payload. */
|
||||
void setScriptedEvents(List<MxEvent> events) {
|
||||
fakeGateway.scriptedEvents.clear();
|
||||
fakeGateway.scriptedEvents.addAll(events);
|
||||
}
|
||||
|
||||
/** Replaces the scripted {@code discoverHierarchy} payload. */
|
||||
void setScriptedObjects(List<GalaxyObject> objects) {
|
||||
fakeGalaxy.scriptedObjects.clear();
|
||||
fakeGalaxy.scriptedObjects.addAll(objects);
|
||||
}
|
||||
|
||||
/** Replaces the scripted {@code watchDeployEvents} payload. */
|
||||
void setScriptedDeployEvents(List<DeployEvent> deployEvents) {
|
||||
fakeGalaxy.scriptedDeployEvents.clear();
|
||||
fakeGalaxy.scriptedDeployEvents.addAll(deployEvents);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the in-process channel into the scripted services.
|
||||
*
|
||||
* @return the managed channel; lifecycle owned by the harness
|
||||
*/
|
||||
ManagedChannel channel() {
|
||||
return channel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a real {@link MxGatewayClient} over the in-process channel.
|
||||
*
|
||||
* @return a client borrowing the harness channel
|
||||
*/
|
||||
MxGatewayClient gatewayClient() {
|
||||
return new MxGatewayClient(channel, testOptions());
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a real {@link GalaxyRepositoryClient} over the in-process channel.
|
||||
*
|
||||
* @return a client borrowing the harness channel
|
||||
*/
|
||||
GalaxyRepositoryClient galaxyClient() {
|
||||
return new GalaxyRepositoryClient(channel, testOptions());
|
||||
}
|
||||
|
||||
private static MxGatewayClientOptions testOptions() {
|
||||
return MxGatewayClientOptions.builder()
|
||||
.endpoint("in-process")
|
||||
.apiKey("mxgw_test_secret")
|
||||
.plaintext(true)
|
||||
.callTimeout(Duration.ofSeconds(5))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
channel.shutdownNow();
|
||||
server.shutdownNow();
|
||||
}
|
||||
|
||||
private static ProtocolStatus ok() {
|
||||
return ProtocolStatus.newBuilder()
|
||||
.setCode(ProtocolStatusCode.PROTOCOL_STATUS_CODE_OK)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** Scripted fake of the {@code MxAccessGateway} service. */
|
||||
private static final class FakeGatewayService extends MxAccessGatewayGrpc.MxAccessGatewayImplBase {
|
||||
private final List<MxEvent> scriptedEvents = new CopyOnWriteArrayList<>();
|
||||
|
||||
FakeGatewayService(List<MxEvent> scriptedEvents) {
|
||||
this.scriptedEvents.addAll(scriptedEvents);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void streamEvents(
|
||||
mxaccess_gateway.v1.MxaccessGateway.StreamEventsRequest request,
|
||||
StreamObserver<MxEvent> responseObserver) {
|
||||
for (MxEvent event : scriptedEvents) {
|
||||
responseObserver.onNext(event);
|
||||
}
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeSession(
|
||||
CloseSessionRequest request, StreamObserver<CloseSessionReply> responseObserver) {
|
||||
responseObserver.onNext(CloseSessionReply.newBuilder()
|
||||
.setSessionId(request.getSessionId())
|
||||
.setFinalState(SessionState.SESSION_STATE_CLOSED)
|
||||
.setProtocolStatus(ok())
|
||||
.build());
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
}
|
||||
|
||||
/** Scripted fake of the {@code GalaxyRepository} service. */
|
||||
private static final class FakeGalaxyService extends GalaxyRepositoryGrpc.GalaxyRepositoryImplBase {
|
||||
private final List<GalaxyObject> scriptedObjects = new CopyOnWriteArrayList<>();
|
||||
private final List<DeployEvent> scriptedDeployEvents = new CopyOnWriteArrayList<>();
|
||||
|
||||
FakeGalaxyService(List<GalaxyObject> scriptedObjects, List<DeployEvent> scriptedDeployEvents) {
|
||||
this.scriptedObjects.addAll(scriptedObjects);
|
||||
this.scriptedDeployEvents.addAll(scriptedDeployEvents);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void discoverHierarchy(
|
||||
DiscoverHierarchyRequest request, StreamObserver<DiscoverHierarchyReply> responseObserver) {
|
||||
List<GalaxyObject> snapshot = new ArrayList<>(scriptedObjects);
|
||||
responseObserver.onNext(DiscoverHierarchyReply.newBuilder()
|
||||
.setTotalObjectCount(snapshot.size())
|
||||
.addAllObjects(snapshot)
|
||||
.setNextPageToken("")
|
||||
.build());
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void watchDeployEvents(
|
||||
WatchDeployEventsRequest request, StreamObserver<DeployEvent> responseObserver) {
|
||||
for (DeployEvent event : scriptedDeployEvents) {
|
||||
responseObserver.onNext(event);
|
||||
}
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
}
|
||||
}
|
||||
+390
@@ -6,6 +6,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.zb.mom.ww.mxgateway.client.MxGatewayAlarmFeedSubscription;
|
||||
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;
|
||||
@@ -31,6 +32,7 @@ import mxaccess_gateway.v1.MxaccessGateway.CloseSessionRequest;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.MxCommandKind;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.MxCommandReply;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.MxEvent;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.MxEventFamily;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.MxValue;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.OnAlarmTransitionEvent;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.OpenSessionReply;
|
||||
@@ -305,6 +307,183 @@ final class MxGatewayCliTests {
|
||||
assertTrue(run.output().contains("\"tagAddress\":\"TestMachine_002.TestChangingInt\""));
|
||||
}
|
||||
|
||||
// ---- read-bulk / write-bulk / write2-bulk subcommands ----
|
||||
|
||||
@Test
|
||||
void readBulkCommandForwardsTimeoutAndPrintsResults() {
|
||||
FakeClientFactory factory = new FakeClientFactory();
|
||||
CliRun run = execute(
|
||||
factory,
|
||||
"read-bulk",
|
||||
"--session-id", "session-cli",
|
||||
"--server-handle", "42",
|
||||
"--items", "TestMachine_001.TestInt,TestMachine_002.TestInt",
|
||||
"--timeout-ms", "750",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode());
|
||||
assertEquals(750, factory.client.session.lastReadBulkTimeoutMs);
|
||||
String out = run.output();
|
||||
assertTrue(out.contains("\"command\":\"read-bulk\""), out);
|
||||
assertTrue(out.contains("\"tagAddress\":\"TestMachine_001.TestInt\""), out);
|
||||
assertTrue(out.contains("\"tagAddress\":\"TestMachine_002.TestInt\""), out);
|
||||
assertTrue(out.contains("\"itemHandle\""), out);
|
||||
assertTrue(out.contains("\"wasCached\""), out);
|
||||
assertTrue(out.contains("\"quality\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeBulkCommandParsesTypedValuesAndPrintsResults() {
|
||||
FakeClientFactory factory = new FakeClientFactory();
|
||||
CliRun run = execute(
|
||||
factory,
|
||||
"write-bulk",
|
||||
"--session-id", "session-cli",
|
||||
"--server-handle", "42",
|
||||
"--item-handles", "100,101",
|
||||
"--type", "int32",
|
||||
"--values", "111,222",
|
||||
"--user-id", "5",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode());
|
||||
List<WriteBulkEntry> entries = factory.client.session.lastWriteBulkEntries;
|
||||
assertEquals(2, entries.size());
|
||||
assertEquals(111, entries.get(0).getValue().getInt32Value());
|
||||
assertEquals(222, entries.get(1).getValue().getInt32Value());
|
||||
assertEquals(5, entries.get(0).getUserId());
|
||||
assertEquals(5, entries.get(1).getUserId());
|
||||
String out = run.output();
|
||||
assertTrue(out.contains("\"command\":\"write-bulk\""), out);
|
||||
assertTrue(out.contains("\"itemHandle\":100"), out);
|
||||
assertTrue(out.contains("\"wasSuccessful\":true"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void write2BulkCommandForwardsTimestampAndPrintsResults() {
|
||||
FakeClientFactory factory = new FakeClientFactory();
|
||||
CliRun run = execute(
|
||||
factory,
|
||||
"write2-bulk",
|
||||
"--session-id", "session-cli",
|
||||
"--server-handle", "42",
|
||||
"--item-handles", "100",
|
||||
"--type", "string",
|
||||
"--values", "hello",
|
||||
"--timestamp", "2026-05-20T00:00:00Z",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode());
|
||||
List<Write2BulkEntry> entries = factory.client.session.lastWrite2BulkEntries;
|
||||
assertEquals(1, entries.size());
|
||||
assertTrue(entries.get(0).hasTimestampValue(), "expected timestampValue to be set");
|
||||
String out = run.output();
|
||||
assertTrue(out.contains("\"command\":\"write2-bulk\""), out);
|
||||
assertTrue(out.contains("\"itemHandle\":100"), out);
|
||||
assertTrue(out.contains("\"wasSuccessful\":true"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeSecuredBulkCommandForwardsUserIdsAndPrintsResults() {
|
||||
FakeClientFactory factory = new FakeClientFactory();
|
||||
CliRun run = execute(
|
||||
factory,
|
||||
"write-secured-bulk",
|
||||
"--session-id", "session-cli",
|
||||
"--server-handle", "42",
|
||||
"--item-handles", "100,101",
|
||||
"--type", "int32",
|
||||
"--values", "10,20",
|
||||
"--current-user-id", "7",
|
||||
"--verifier-user-id", "8",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode());
|
||||
List<WriteSecuredBulkEntry> entries = factory.client.session.lastWriteSecuredBulkEntries;
|
||||
assertEquals(2, entries.size());
|
||||
assertEquals(7, entries.get(0).getCurrentUserId());
|
||||
assertEquals(8, entries.get(0).getVerifierUserId());
|
||||
assertEquals(7, entries.get(1).getCurrentUserId());
|
||||
assertEquals(8, entries.get(1).getVerifierUserId());
|
||||
assertEquals(10, entries.get(0).getValue().getInt32Value());
|
||||
assertEquals(20, entries.get(1).getValue().getInt32Value());
|
||||
String out = run.output();
|
||||
assertTrue(out.contains("\"command\":\"write-secured-bulk\""), out);
|
||||
assertTrue(out.contains("\"itemHandle\":100"), out);
|
||||
assertTrue(out.contains("\"wasSuccessful\":true"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writeSecured2BulkCommandForwardsTimestampAndUserIdsAndPrintsResults() {
|
||||
FakeClientFactory factory = new FakeClientFactory();
|
||||
CliRun run = execute(
|
||||
factory,
|
||||
"write-secured2-bulk",
|
||||
"--session-id", "session-cli",
|
||||
"--server-handle", "42",
|
||||
"--item-handles", "100",
|
||||
"--type", "string",
|
||||
"--values", "hello",
|
||||
"--timestamp", "2026-05-20T00:00:00Z",
|
||||
"--current-user-id", "7",
|
||||
"--verifier-user-id", "8",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode());
|
||||
List<WriteSecured2BulkEntry> entries = factory.client.session.lastWriteSecured2BulkEntries;
|
||||
assertEquals(1, entries.size());
|
||||
assertEquals(7, entries.get(0).getCurrentUserId());
|
||||
assertEquals(8, entries.get(0).getVerifierUserId());
|
||||
assertTrue(entries.get(0).hasTimestampValue(), "expected timestampValue to be set");
|
||||
String out = run.output();
|
||||
assertTrue(out.contains("\"command\":\"write-secured2-bulk\""), out);
|
||||
assertTrue(out.contains("\"itemHandle\":100"), out);
|
||||
assertTrue(out.contains("\"wasSuccessful\":true"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void benchReadBulkCommandEmitsJsonSchemaKeys() {
|
||||
FakeClientFactory factory = new FakeClientFactory();
|
||||
CliRun run = execute(
|
||||
factory,
|
||||
"bench-read-bulk",
|
||||
"--session-id", "session-cli",
|
||||
"--server-handle", "42",
|
||||
"--items", "TestMachine_001.TestInt",
|
||||
"--iterations", "3",
|
||||
"--warmup", "0",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode());
|
||||
String out = run.output();
|
||||
assertTrue(out.contains("\"command\":\"bench-read-bulk\""), out);
|
||||
assertTrue(out.contains("\"iterations\""), out);
|
||||
assertTrue(out.contains("\"warmup\""), out);
|
||||
assertTrue(out.contains("\"tagCount\""), out);
|
||||
assertTrue(out.contains("\"resultCount\""), out);
|
||||
assertTrue(out.contains("\"successCount\""), out);
|
||||
assertTrue(out.contains("\"cachedCount\""), out);
|
||||
assertTrue(out.contains("\"avgMs\""), out);
|
||||
assertTrue(out.contains("\"minMs\""), out);
|
||||
assertTrue(out.contains("\"maxMs\""), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void closeSessionCommandPrintsReply() {
|
||||
FakeClientFactory factory = new FakeClientFactory();
|
||||
CliRun run = execute(
|
||||
factory,
|
||||
"close-session",
|
||||
"--session-id", "session-cli",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode());
|
||||
assertTrue(factory.client.closeCalled);
|
||||
String out = run.output();
|
||||
assertTrue(out.contains("\"command\":\"close-session\""), out);
|
||||
assertTrue(out.contains("SESSION_STATE_CLOSED"), out);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsubscribeBulkCommandPrintsResults() {
|
||||
CliRun run = execute(
|
||||
@@ -516,6 +695,143 @@ final class MxGatewayCliTests {
|
||||
+ " out=\n" + run.output() + "\nerr=\n" + run.errors());
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamEventsRendersScriptedEventsIncludingHighUint64Sequence() {
|
||||
// Drive the REAL MxGatewayClient / MxGatewaySession / MxEventStream
|
||||
// path over the in-process harness (Task 4), so the production
|
||||
// stream-events command exercises the real streaming wrapper instead
|
||||
// of a hand-written FakeSession seam.
|
||||
//
|
||||
// The high worker-sequence (-1L == 18446744073709551615 unsigned)
|
||||
// covers the unsigned-rendering regression: worker_sequence is a
|
||||
// proto uint64 carried as a Java long with the top bit set. The CLI's
|
||||
// --json path renders it through protobuf's JsonFormat, which prints
|
||||
// uint64 as an unsigned decimal STRING; a naive %d render would print
|
||||
// a negative number instead.
|
||||
MxEvent dataChange = MxEvent.newBuilder()
|
||||
.setFamily(MxEventFamily.MX_EVENT_FAMILY_ON_DATA_CHANGE)
|
||||
.setSessionId("session-cli")
|
||||
.setServerHandle(7)
|
||||
.setItemHandle(42)
|
||||
.setWorkerSequence(5L)
|
||||
.build();
|
||||
MxEvent highSequence = MxEvent.newBuilder()
|
||||
.setFamily(MxEventFamily.MX_EVENT_FAMILY_OPERATION_COMPLETE)
|
||||
.setSessionId("session-cli")
|
||||
.setServerHandle(9)
|
||||
.setItemHandle(99)
|
||||
// -1L unsigned == 18446744073709551615 (top bit set).
|
||||
.setWorkerSequence(-1L)
|
||||
.build();
|
||||
|
||||
try (InProcessGatewayHarness harness = new InProcessGatewayHarness()) {
|
||||
harness.setScriptedEvents(List.of(dataChange, highSequence));
|
||||
CliRun run = execute(
|
||||
new HarnessClientFactory(harness),
|
||||
"stream-events",
|
||||
"--session-id",
|
||||
"session-cli",
|
||||
"--json");
|
||||
|
||||
assertEquals(0, run.exitCode(), "errors:\n" + run.errors());
|
||||
String out = run.output();
|
||||
// Scripted event fields surface in the JSON render.
|
||||
assertTrue(out.contains("\"family\":\"MX_EVENT_FAMILY_ON_DATA_CHANGE\""), out);
|
||||
assertTrue(out.contains("\"family\":\"MX_EVENT_FAMILY_OPERATION_COMPLETE\""), out);
|
||||
assertTrue(out.contains("\"serverHandle\":7"), out);
|
||||
assertTrue(out.contains("\"itemHandle\":42"), out);
|
||||
// The low sequence renders as the unsigned decimal string "5".
|
||||
assertTrue(out.contains("\"workerSequence\":\"5\""), out);
|
||||
// The high sequence renders as the FULL unsigned decimal, not -1.
|
||||
assertTrue(out.contains("\"workerSequence\":\"18446744073709551615\""), out);
|
||||
assertFalse(out.contains("\"workerSequence\":\"-1\""), out);
|
||||
assertFalse(out.contains("\"workerSequence\":-1"), out);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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");
|
||||
@@ -630,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) {
|
||||
}
|
||||
|
||||
@@ -672,6 +1006,50 @@ final class MxGatewayCliTests {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory that wires the production {@link MxGatewayCli.GrpcMxGatewayCliClient}
|
||||
* 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
|
||||
* client construction for the harness-backed client.
|
||||
*/
|
||||
private static final class HarnessClientFactory implements MxGatewayCli.MxGatewayCliClientFactory {
|
||||
private final InProcessGatewayHarness harness;
|
||||
|
||||
private HarnessClientFactory(InProcessGatewayHarness harness) {
|
||||
this.harness = harness;
|
||||
}
|
||||
|
||||
@Override
|
||||
public MxGatewayCli.MxGatewayCliClient connect(MxGatewayCli.CommonOptions options) {
|
||||
return new MxGatewayCli.GrpcMxGatewayCliClient(
|
||||
harness.gatewayClient(), options.spec.commandLine().getOut());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
@@ -815,6 +1193,12 @@ final class MxGatewayCliTests {
|
||||
private boolean adviseCalled;
|
||||
private MxValue lastWriteValue;
|
||||
private String lastPingMessage;
|
||||
private long lastReadBulkTimeoutMs;
|
||||
private List<String> lastReadBulkItems;
|
||||
private List<WriteBulkEntry> lastWriteBulkEntries;
|
||||
private List<Write2BulkEntry> lastWrite2BulkEntries;
|
||||
private List<WriteSecuredBulkEntry> lastWriteSecuredBulkEntries;
|
||||
private List<WriteSecured2BulkEntry> lastWriteSecured2BulkEntries;
|
||||
|
||||
@Override
|
||||
public MxCommandReply pingRaw(String message) {
|
||||
@@ -912,6 +1296,8 @@ final class MxGatewayCliTests {
|
||||
|
||||
@Override
|
||||
public List<BulkReadResult> readBulk(int serverHandle, List<String> items, Duration timeout) {
|
||||
lastReadBulkTimeoutMs = timeout.toMillis();
|
||||
lastReadBulkItems = new ArrayList<>(items);
|
||||
List<BulkReadResult> results = new ArrayList<>();
|
||||
for (int index = 0; index < items.size(); index++) {
|
||||
results.add(BulkReadResult.newBuilder()
|
||||
@@ -927,6 +1313,7 @@ final class MxGatewayCliTests {
|
||||
|
||||
@Override
|
||||
public List<BulkWriteResult> writeBulk(int serverHandle, List<WriteBulkEntry> entries) {
|
||||
lastWriteBulkEntries = new ArrayList<>(entries);
|
||||
List<BulkWriteResult> results = new ArrayList<>();
|
||||
for (WriteBulkEntry entry : entries) {
|
||||
results.add(BulkWriteResult.newBuilder()
|
||||
@@ -940,6 +1327,7 @@ final class MxGatewayCliTests {
|
||||
|
||||
@Override
|
||||
public List<BulkWriteResult> write2Bulk(int serverHandle, List<Write2BulkEntry> entries) {
|
||||
lastWrite2BulkEntries = new ArrayList<>(entries);
|
||||
List<BulkWriteResult> results = new ArrayList<>();
|
||||
for (Write2BulkEntry entry : entries) {
|
||||
results.add(BulkWriteResult.newBuilder()
|
||||
@@ -953,6 +1341,7 @@ final class MxGatewayCliTests {
|
||||
|
||||
@Override
|
||||
public List<BulkWriteResult> writeSecuredBulk(int serverHandle, List<WriteSecuredBulkEntry> entries) {
|
||||
lastWriteSecuredBulkEntries = new ArrayList<>(entries);
|
||||
List<BulkWriteResult> results = new ArrayList<>();
|
||||
for (WriteSecuredBulkEntry entry : entries) {
|
||||
results.add(BulkWriteResult.newBuilder()
|
||||
@@ -966,6 +1355,7 @@ final class MxGatewayCliTests {
|
||||
|
||||
@Override
|
||||
public List<BulkWriteResult> writeSecured2Bulk(int serverHandle, List<WriteSecured2BulkEntry> entries) {
|
||||
lastWriteSecured2BulkEntries = new ArrayList<>(entries);
|
||||
List<BulkWriteResult> results = new ArrayList<>();
|
||||
for (WriteSecured2BulkEntry entry : entries) {
|
||||
results.add(BulkWriteResult.newBuilder()
|
||||
|
||||
@@ -39,7 +39,8 @@ paths, timeouts, queue sizes, enum values, or protocol values are invalid.
|
||||
"LeaseSweepIntervalSeconds": 30,
|
||||
"DetachGraceSeconds": 30,
|
||||
"AllowMultipleEventSubscribers": false,
|
||||
"MaxEventSubscribersPerSession": 8
|
||||
"MaxEventSubscribersPerSession": 8,
|
||||
"WorkerReadyWaitTimeoutMs": 0
|
||||
},
|
||||
"Events": {
|
||||
"QueueCapacity": 10000,
|
||||
@@ -130,6 +131,7 @@ to avoid accidental large allocations from malformed or oversized frames.
|
||||
| `MxGateway:Sessions:DetachGraceSeconds` | `30` | Detach-grace retention window. When positive, a session whose last external (gRPC) event-stream subscriber drops is retained in `Ready` for this many seconds so a client can reconnect; if no external subscriber re-attaches within the window, the lease monitor closes it with `detach-grace-expired`. The internal dashboard mirror does not count as an external subscriber, so a dashboard-only session still enters detach-grace. `0` disables retention and reverts to closing only on normal lease expiry. Must be zero or greater. Reconnect/replay itself is implemented separately (Task 12); this option controls retention and expiry only. The effective close happens within the next sweep cycle after the window elapses — up to `LeaseSweepIntervalSeconds` after expiry. Operators wanting a firm minimum retention bound should set `DetachGraceSeconds` greater than `LeaseSweepIntervalSeconds`. |
|
||||
| `MxGateway:Sessions:AllowMultipleEventSubscribers` | `false` | Controls whether multiple `StreamEvents` subscribers may attach to one session. When `false` the session refuses a second subscriber with `AlreadyExists`. Set to `true` to enable fan-out via the `SessionEventDistributor`. |
|
||||
| `MxGateway:Sessions:MaxEventSubscribersPerSession` | `8` | Maximum number of concurrent `StreamEvents` subscribers per session when `AllowMultipleEventSubscribers` is `true`. Effectively 1 when `AllowMultipleEventSubscribers` is `false`. Must be greater than zero. |
|
||||
| `MxGateway:Sessions:WorkerReadyWaitTimeoutMs` | `0` | Bounded time, in milliseconds, the gateway will wait for a worker to reach `Ready` when the session is already `Ready` but the worker state has transiently diverged (e.g. `Handshaking` after a heartbeat blip). Applies only to transient worker states; terminal states (`Faulted`/`Closing`/`Closed`/no worker) fail fast immediately regardless of this setting. `0` (the default) disables the wait and preserves the original fail-fast behavior. Must be greater than or equal to zero. |
|
||||
|
||||
All numeric session options must be greater than zero.
|
||||
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
# Still-Pending §8 Completion — Design
|
||||
|
||||
> **Status:** Approved 2026-06-16. Next step: `superpowers-extended-cc:writing-plans`.
|
||||
|
||||
**Goal:** Close the actionable items in `stillpending.md` §8 ("Deferred test-coverage
|
||||
follow-ups, never filed as findings") — the only Bucket-A work that is neither
|
||||
vendor-gated nor live-rig-gated and is not already covered by the session-resilience
|
||||
epic plan.
|
||||
|
||||
**Scope decision:** Bucket A only (actionable code/test work). The session-resilience
|
||||
epic (Tasks 13–28) is already planned in `docs/plans/2026-06-15-session-resilience.md`
|
||||
and is explicitly **out of scope** here — resume it separately. Vendor-gated
|
||||
(§1.4/§3.4/§3.5) and live-rig/capture-gated (§1.3/§3.x/§5/§6.1) items cannot be
|
||||
completed from this dev box and are out of scope.
|
||||
|
||||
**Approach:** "C" — the complete option, including new in-process gRPC test
|
||||
infrastructure for the Java streaming/galaxy CLI commands and a full bounded
|
||||
ready-wait in the gateway session hot path.
|
||||
|
||||
---
|
||||
|
||||
## Important correction (verified 2026-06-16)
|
||||
|
||||
The three §8 items cite findings marked **Resolved** in the review backlog, but those
|
||||
resolutions did **not** survive into the current tree:
|
||||
|
||||
- The Java bulk-family CLI tests that `Client.Java-026` (resolved 2026-05-20) describes
|
||||
were written against the old `com.dohertylan.mxgateway` package. After the rename to
|
||||
`com.zb.mom.ww`, the current
|
||||
`clients/java/zb-mom-ww-mxgateway-cli/.../MxGatewayCliTests.java` has **zero** coverage
|
||||
for `read-bulk`, `write-bulk`, `write2-bulk`, `write-secured-bulk`,
|
||||
`write-secured2-bulk`, `bench-read-bulk`, `stream-events`, `close-session`,
|
||||
`galaxy-discover`, `galaxy-watch`. (`galaxy-test-connection`/`galaxy-last-deploy`/
|
||||
`galaxy-browse`/`stream-alarms` **do** have tests now.)
|
||||
- `Server-030` (both states in the not-ready diagnostic) **is** done — confirmed at
|
||||
`src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs:1676`. The *deferred
|
||||
follow-up* — should the gateway briefly wait for worker-Ready before failing fast? —
|
||||
is genuinely unbuilt.
|
||||
- `Tests-023` extracted a canonical `TestSupport/FakeWorkerProcess(int)`, yet three test
|
||||
files still define private nested copies.
|
||||
|
||||
So §8's gap is real and current.
|
||||
|
||||
---
|
||||
|
||||
## Workstreams
|
||||
|
||||
Four independently landable workstreams.
|
||||
|
||||
| WS | Title | Files (language) | Classification | Depends on |
|
||||
|----|-------|------------------|----------------|------------|
|
||||
| A | Synchronous Java CLI tests (7 commands) | Java CLI test | small | — |
|
||||
| B | In-process gRPC harness + streaming/galaxy CLI tests (3 commands) | Java CLI test + small CLI seam | standard | A (shares test file) |
|
||||
| C | Worker-Ready bounded ready-wait | C# server session hot path | high-risk | — |
|
||||
| D | `FakeWorkerProcess` consolidation | C# tests | small | — |
|
||||
|
||||
A, C, D are mutually independent (disjoint files/languages) and may be dispatched in
|
||||
parallel. B follows A because both edit `MxGatewayCliTests.java`.
|
||||
|
||||
---
|
||||
|
||||
## WS-A — Synchronous Java CLI tests
|
||||
|
||||
**What:** Round-trip CLI tests for the 7 commands testable through the existing
|
||||
`FakeSession`/`FakeClient` seam (the same seam `subscribe-bulk`/`write` already use):
|
||||
`read-bulk`, `write-bulk`, `write2-bulk`, `write-secured-bulk`, `write-secured2-bulk`,
|
||||
`bench-read-bulk`, `close-session`.
|
||||
|
||||
**How:** Upgrade `FakeSession` (currently returns empty lists) to per-call recorders
|
||||
that capture the parsed entries (timeout, typed values via the shared `parseValue(type,
|
||||
text)` switch, user-ids, timestamp) and synthesize one `BulkReadResult`/`BulkWriteResult`
|
||||
per requested handle, so JSON-shape assertions exercise the
|
||||
`bulkReadResultMap`/`bulkWriteResultMap` serializers. One `@Test` per command:
|
||||
|
||||
- `read-bulk`: `--timeout-ms` reaches session; JSON carries `tagAddress`/`itemHandle`/
|
||||
`wasCached`/`quality`.
|
||||
- `write-bulk`: `--type int32 --values 111,222 --user-id 5` parses through `parseValue`;
|
||||
entries built with the expected typed `MxValue` + `userId`.
|
||||
- `write2-bulk`: `--timestamp …Z` reaches the entry as `timestampValue`
|
||||
(`hasTimestampValue()` true).
|
||||
- `write-secured-bulk`: `--current-user-id`/`--verifier-user-id` both propagate.
|
||||
- `write-secured2-bulk`: timestamp + both user-ids.
|
||||
- `bench-read-bulk`: 1s steady / 0s warmup; assert cross-language schema keys
|
||||
(`language=java`, `command=bench-read-bulk`, `totalCalls`, `successfulCalls`,
|
||||
`failedCalls`, `callsPerSecond`, `latencyMs.p50/p95/p99`).
|
||||
- `close-session`: `CloseSessionReply` round-trips through `FakeClient`.
|
||||
|
||||
**Verify:** `gradle :zb-mom-ww-mxgateway-cli:test --tests *MxGatewayCliTests`.
|
||||
|
||||
---
|
||||
|
||||
## WS-B — In-process gRPC harness + streaming/galaxy CLI tests
|
||||
|
||||
**Why infra is required:** `MxEventStream` and `DeployEventStream` have package-private
|
||||
constructors; `GalaxyRepositoryClient` is `final` with a static `connect()` and
|
||||
`GalaxyCommand` has **no** injectable factory. None of `stream-events`/`galaxy-watch`/
|
||||
`galaxy-discover` can be faked through the `FakeSession` seam.
|
||||
|
||||
**What:** A JUnit fixture that starts a gRPC **`InProcessServer`** hosting scripted
|
||||
`MxAccessGateway` + `GalaxyRepository` service implementations and exposes an in-process
|
||||
`Channel`. The **real** `MxGatewayClient`/`GalaxyRepositoryClient` connect to it, so the
|
||||
real `MxEventStream`/`DeployEventStream` queue-draining and `GalaxyRepositoryClient`
|
||||
paging are exercised end-to-end (highest fidelity; no reflection, no package hacks).
|
||||
|
||||
- **Production change (CLI module only, not the library):** add a `GalaxyClientFactory`
|
||||
seam to `GalaxyCommand` mirroring the existing `MxGatewayCliClientFactory`, so galaxy
|
||||
commands can target the in-process channel.
|
||||
- `stream-events`: server streams a scripted `MxEvent` sequence → assert CLI render,
|
||||
including the unsigned-uint64 worker-sequence regression.
|
||||
- `galaxy-watch`: server streams scripted deploy events → assert CLI feed output.
|
||||
- `galaxy-discover`: server returns a paged `GalaxyObject` hierarchy → assert CLI JSON.
|
||||
|
||||
The 7 synchronous commands stay on the lightweight `FakeSession` seam (YAGNI — no reason
|
||||
to route them through a server).
|
||||
|
||||
**Verify:** `gradle :zb-mom-ww-mxgateway-cli:test --tests *MxGatewayCliTests`.
|
||||
|
||||
---
|
||||
|
||||
## WS-C — Worker-Ready bounded ready-wait
|
||||
|
||||
**Problem:** `GetReadyWorkerClient` (`GatewaySession.cs:1665`) fails fast when the session
|
||||
is `Ready` but the worker client's `WorkerClientState` has diverged (`Handshaking` after a
|
||||
heartbeat blip, etc.). The both-states diagnostic exists; a brief wait does not.
|
||||
|
||||
**Constraint:** the check runs inside the `_syncRoot` lock — we cannot sleep/poll there.
|
||||
|
||||
**Design (pinned decisions):**
|
||||
|
||||
- New `GetReadyWorkerClientAsync`: read state under `_syncRoot`; **if** session is `Ready`
|
||||
but worker is **transient** (`Handshaking`/`Created`), release the lock, poll at a short
|
||||
interval (e.g. 25 ms) until the worker reaches `Ready` or a bounded timeout elapses, then
|
||||
re-check under the lock.
|
||||
- **Terminal worker states (`Faulted`/`Closing`/`Closed`/null) fail fast immediately** —
|
||||
never wait; retrying a faulted worker is pointless and would mask the fault.
|
||||
- New config `MxGateway:Sessions:WorkerReadyWaitTimeout` on `GatewaySessionOptions`,
|
||||
**default `0` = disabled** (preserves today's exact fail-fast behavior unless opted in),
|
||||
validated `>= 0` by the options validator. Document in `docs/GatewayConfiguration.md`.
|
||||
- The both-states diagnostic is preserved for the final failure. Callers at
|
||||
`GatewaySession.cs:918` and `:1263` become `await`.
|
||||
|
||||
**Tests:**
|
||||
- Handshaking→Ready within the timeout succeeds (worker invoked once).
|
||||
- Faulted fails fast with both states in the message, zero waiting.
|
||||
- Timeout elapses → fails with both states.
|
||||
- Default `0` → unchanged fail-fast (no wait, no behavior change).
|
||||
|
||||
**Verify:** `dotnet test src/ZB.MOM.WW.MxGateway.Tests --filter "FullyQualifiedName~SessionManager"`
|
||||
(plus the options-validator test class).
|
||||
|
||||
---
|
||||
|
||||
## WS-D — `FakeWorkerProcess` consolidation
|
||||
|
||||
**What:** Replace the private nested `FakeWorkerProcess` in
|
||||
`SessionWorkerClientFactoryFakeWorkerTests`, `WorkerProcessLauncherTests`, and
|
||||
`WorkerClientTests` with the canonical `TestSupport/FakeWorkerProcess(int)` (which already
|
||||
has `MarkExited`/`Kill`/TCS-backed `WaitForExitAsync`). Where a nested copy carries extra
|
||||
behavior the canonical lacks, fold that into the canonical first, then delete the copies.
|
||||
|
||||
**Verify:** `dotnet test src/ZB.MOM.WW.MxGateway.Tests --filter "FullyQualifiedName~WorkerClient | FullyQualifiedName~WorkerProcessLauncher | FullyQualifiedName~SessionWorkerClientFactory"`.
|
||||
|
||||
---
|
||||
|
||||
## Testing & sequencing
|
||||
|
||||
Per the targeted-test rule in `CLAUDE.md` (Source Update Workflow): each task runs only
|
||||
its own filtered tests. Run the full gateway suite at most once, after WS-C + WS-D land.
|
||||
|
||||
Out-of-scope items remain recorded in `stillpending.md` (vendor/rig-gated) and the
|
||||
session-resilience epic (`oldtasks.md`).
|
||||
@@ -0,0 +1,327 @@
|
||||
# Still-Pending §8 Completion Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:executing-plans (or subagent-driven-development) to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Close the three actionable `stillpending.md` §8 test-coverage follow-ups — Java CLI coverage for the 10 untested subcommands, the gateway Worker-Ready bounded ready-wait, and the `FakeWorkerProcess` de-duplication.
|
||||
|
||||
**Architecture:** Four independent workstreams. Java CLI tests split into a synchronous tier (existing `FakeSession` seam) and a streaming/galaxy tier (new in-process gRPC harness over the *real* client, using the public `Channel` constructors that already exist). C# work adds an opt-in bounded ready-wait in the session hot path (default off = no behavior change) and consolidates three duplicate test fakes onto the canonical `TestSupport/FakeWorkerProcess`.
|
||||
|
||||
**Tech Stack:** Java 21 + Gradle + picocli + grpc-java (`grpc-inprocess`, `grpc-testing`); .NET 10 + xUnit.
|
||||
|
||||
**Design doc:** `docs/plans/2026-06-16-stillpending-section8-design.md`. Branch: `feat/stillpending-section8`.
|
||||
|
||||
**Key facts verified during planning:**
|
||||
- `clients/java/.../cli/MxGatewayCli.java`: `GatewayCommand` has a `clientFactory` (`MxGatewayCliClientFactory`) seam tests already override; `GalaxyCommand.connect()` (line ~368) calls the *static* `GalaxyRepositoryClient.connect(...)` with **no** injectable seam. The `FakeSession`/`FakeClient`/`FakeClientFactory` test doubles live in `MxGatewayCliTests.java` (~lines 636–984).
|
||||
- `MxGatewayClient(Channel, MxGatewayClientOptions)` and `GalaxyRepositoryClient(Channel, MxGatewayClientOptions)` are **public** constructors (line 67 of each) — point them at an in-process channel, no library change needed.
|
||||
- `grpc-inprocess` + `grpc-testing` are test deps in the **client** module only; the **cli** module's `build.gradle` needs them added.
|
||||
- C#: option class is `SessionOptions` (`src/ZB.MOM.WW.MxGateway.Server/Configuration/SessionOptions.cs`), config section `MxGateway:Sessions`, `{ get; init; }` style. `GetReadyWorkerClient()` is at `GatewaySession.cs:1665`; callers are `InvokeAsync` (`:918`, already async) and `ReadEventsAsync` (`:1263`, returns `IAsyncEnumerable` non-async — must become an async iterator).
|
||||
|
||||
**Out of scope:** Session-resilience epic (Tasks 13–28, see `docs/plans/2026-06-15-session-resilience.md`); vendor/rig-gated §1.3/§1.4/§3.x/§5/§6.1 items.
|
||||
|
||||
**Testing rule (CLAUDE.md):** Each task runs ONLY its own filtered tests. Full gateway suite at most once, after Tasks 8 + 9 land.
|
||||
|
||||
---
|
||||
|
||||
## Workstream / dependency overview
|
||||
|
||||
| Task | WS | Title | Class | Files | blockedBy | ∥ with |
|
||||
|------|----|-------|-------|-------|-----------|--------|
|
||||
| 1 | A | FakeSession recorders + read/write/write2-bulk tests | small | cli test | — | 3,4,7,9 |
|
||||
| 2 | A | secured/secured2/bench-bulk + close-session tests | small | cli test | 1 | 3,4,7,9 |
|
||||
| 3 | B | GalaxyClientFactory seam + cli grpc test deps | small | cli main + build.gradle | — | 1,2,4,7,8,9 |
|
||||
| 4 | B | In-process gRPC harness fixture | standard | new cli test file | — | 1,2,3,7,8,9 |
|
||||
| 5 | B | stream-events test via harness | standard | cli test | 2,4 | 7,8,9 |
|
||||
| 6 | B | galaxy-watch + galaxy-discover tests via harness | standard | cli test | 3,5 | 7,8,9 |
|
||||
| 7 | C | WorkerReadyWaitTimeoutMs option + validator + doc | small | C# config + doc | — | all Java |
|
||||
| 8 | C | Bounded ready-wait in GatewaySession + tests | high-risk | C# server + test | 7 | all Java, 9 |
|
||||
| 9 | D | FakeWorkerProcess consolidation | standard | C# tests | — | all |
|
||||
|
||||
---
|
||||
|
||||
## Task 1: FakeSession recorders + read-bulk / write-bulk / write2-bulk CLI tests
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** Task 3, 4, 7, 9
|
||||
|
||||
**Files:**
|
||||
- Test: `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java`
|
||||
|
||||
**Context:** `FakeSession` (a `MxGatewayCli.MxGatewayCliSession` impl, ~line 812) currently returns empty lists from `readBulk`/`writeBulk`/`write2Bulk`. Empty returns make CLI JSON-shape assertions vacuous. Mirror the existing `subscribeBulkCommandPrintsResults` test style (uses `FakeClientFactory` → `execute(...)` → asserts on captured stdout JSON).
|
||||
|
||||
**Step 1: Upgrade `FakeSession` to record + synthesize.** Add fields capturing the last call args (e.g. `lastReadBulkTimeoutMs`, `lastReadBulkItems`, `lastWriteBulkEntries`, `lastWrite2BulkEntries`) and change `readBulk`/`writeBulk`/`write2Bulk` to synthesize **one** result per requested handle: a `BulkReadResult` carrying `tagAddress`, `itemHandle`, `wasCached`, `quality`; a `BulkWriteResult` carrying the handle + an `Ok` status. Keep empty-list default only when no handles requested.
|
||||
|
||||
**Step 2: Write the three failing tests:**
|
||||
- `readBulkCommandForwardsTimeoutAndPrintsResults` — run `read-bulk` with `--timeout-ms 750` + two tags; assert `lastReadBulkTimeoutMs == 750` and the stdout JSON carries per-tag `tagAddress`/`itemHandle`/`wasCached`/`quality`.
|
||||
- `writeBulkCommandParsesTypedValuesAndPrintsResults` — `--type int32 --values 111,222 --user-id 5`; assert entries parsed through the shared `parseValue` switch into typed `MxValue`s with `userId==5`, and JSON shows the `bulkWriteResultMap`.
|
||||
- `write2BulkCommandForwardsTimestampAndPrintsResults` — `--timestamp 2026-05-20T00:00:00Z`; assert the entry's `hasTimestampValue()` is true.
|
||||
|
||||
**Step 3: Run them and confirm they fail** (empty/zero before the recorder upgrade):
|
||||
`gradle :zb-mom-ww-mxgateway-cli:test --tests '*MxGatewayCliTests'` (from `clients/java`).
|
||||
|
||||
**Step 4: With the Step-1 recorder in place, run again — expect PASS.**
|
||||
|
||||
**Step 5: Commit.**
|
||||
```bash
|
||||
git add clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java
|
||||
git commit -m "test(java-cli): cover read-bulk/write-bulk/write2-bulk round trips"
|
||||
```
|
||||
|
||||
**Acceptance:** 3 new green tests; `FakeSession` records args and returns one row per handle.
|
||||
|
||||
---
|
||||
|
||||
## Task 2: secured / secured2 / bench-read-bulk + close-session CLI tests
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** Task 3, 4, 7, 9
|
||||
**blockedBy:** Task 1 (same test file + shared `FakeSession` recorders)
|
||||
|
||||
**Files:**
|
||||
- Test: `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java`
|
||||
|
||||
**Step 1: Extend `FakeSession`/`FakeClient` recorders** for `writeSecuredBulk`/`writeSecured2Bulk` (capture `currentUserId`/`verifierUserId`) and add a `CloseSessionReply` recorder to `FakeClient` for `closeSession`.
|
||||
|
||||
**Step 2: Write the four failing tests:**
|
||||
- `writeSecuredBulkCommandForwardsUserIdsAndPrintsResults` — `--current-user-id 7 --verifier-user-id 8`; assert both propagate.
|
||||
- `writeSecured2BulkCommandForwardsTimestampAndUserIdsAndPrintsResults` — timestamp + both user-ids.
|
||||
- `benchReadBulkCommandEmitsJsonSchemaKeys` — `--duration-seconds 1 --warmup-seconds 0`; assert the JSON contains `language=java`, `command=bench-read-bulk`, `bulkSize`, `totalCalls`, `successfulCalls`, `failedCalls`, `callsPerSecond`, `latencyMs.p50/p95/p99`, and the synthesized `tags`. Assert schema keys, NOT numeric values.
|
||||
- `closeSessionCommandPrintsReply` — assert the `CloseSessionReply` round-trips to stdout.
|
||||
|
||||
**Step 3–4: Run failing → implement recorders → run PASS** (same gradle command as Task 1, narrowed `--tests '*MxGatewayCliTests'`).
|
||||
|
||||
**Step 5: Commit** `test(java-cli): cover secured/secured2/bench bulk + close-session`.
|
||||
|
||||
**Acceptance:** 4 new green tests; bench test pins schema keys only.
|
||||
|
||||
---
|
||||
|
||||
## Task 3: GalaxyClientFactory seam + cli grpc test deps
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** Task 1, 2, 4, 7, 8, 9
|
||||
|
||||
**Files:**
|
||||
- Modify: `clients/java/zb-mom-ww-mxgateway-cli/src/main/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCli.java` (`GalaxyCommand`, ~lines 361–371; `connect()` ~line 368)
|
||||
- Modify: `clients/java/zb-mom-ww-mxgateway-cli/build.gradle`
|
||||
|
||||
**Context:** `GalaxyCommand.connect()` hard-calls `GalaxyRepositoryClient.connect(...)`. Mirror the existing `MxGatewayCliClientFactory` seam so tests can supply an in-process-backed client.
|
||||
|
||||
**Step 1: Add the seam.** Introduce an interface `GalaxyClientFactory { GalaxyRepositoryClient connect(MxGatewayClientOptions options); }`, give `GalaxyCommand` a `final GalaxyClientFactory galaxyClientFactory` field (constructor-injected, defaulting to `GalaxyRepositoryClient::connect` for production wiring), and change `connect()` to delegate to it. Thread the factory through the picocli command construction the same way `clientFactory` is threaded for gateway commands. Keep the default production path identical (no behavior change).
|
||||
|
||||
**Step 2: Add test deps** to `clients/java/zb-mom-ww-mxgateway-cli/build.gradle`:
|
||||
```gradle
|
||||
testImplementation "io.grpc:grpc-inprocess:${grpcVersion}"
|
||||
testImplementation "io.grpc:grpc-testing:${grpcVersion}"
|
||||
```
|
||||
|
||||
**Step 3: Build to confirm wiring compiles + production galaxy commands still resolve:**
|
||||
`gradle :zb-mom-ww-mxgateway-cli:compileJava :zb-mom-ww-mxgateway-cli:compileTestJava` (from `clients/java`).
|
||||
|
||||
**Step 4: Run the existing galaxy CLI tests to confirm no regression:**
|
||||
`gradle :zb-mom-ww-mxgateway-cli:test --tests '*MxGatewayCliTests'`.
|
||||
|
||||
**Step 5: Commit** `feat(java-cli): inject GalaxyClientFactory seam; add grpc inprocess test deps`.
|
||||
|
||||
**Acceptance:** Seam present, default wiring unchanged, existing galaxy tests green, in-process deps available to the test source set.
|
||||
|
||||
---
|
||||
|
||||
## Task 4: In-process gRPC harness fixture
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** Task 1, 2, 3, 7, 8, 9
|
||||
|
||||
**Files:**
|
||||
- Create: `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/InProcessGatewayHarness.java`
|
||||
|
||||
**Context:** Streaming/galaxy commands can't use `FakeSession` (real `MxEventStream`/`DeployEventStream` package-private ctors; `GalaxyRepositoryClient` final). Drive the *real* client over an in-process channel against scripted fake services. The public `MxGatewayClient(Channel, options)` / `GalaxyRepositoryClient(Channel, options)` ctors make this clean.
|
||||
|
||||
**Step 1: Build the fixture** — `AutoCloseable`, unique server name per instance:
|
||||
- Start `InProcessServerBuilder.forName(name).directExecutor().addService(fakeGateway).addService(fakeGalaxy).build().start()`.
|
||||
- Expose `ManagedChannel channel()` via `InProcessChannelBuilder.forName(name).directExecutor().build()`.
|
||||
- `fakeGateway` extends `MxAccessGatewayGrpc.MxAccessGatewayImplBase`, overriding `streamEvents` (push a scripted `List<MxEvent>` to the `StreamObserver`, then `onCompleted`) and `closeSession`. `fakeGalaxy` extends `GalaxyRepositoryGrpc.GalaxyRepositoryImplBase`, overriding `discoverHierarchy` (return a small paged `GalaxyObject` set) and `watchDeployEvents` (stream scripted deploy events). Make the scripted payloads settable on the harness (constructor args or setters).
|
||||
- Provide helpers: `MxGatewayClient gatewayClient()` → `new MxGatewayClient(channel(), testOptions())`; `GalaxyRepositoryClient galaxyClient()` → `new GalaxyRepositoryClient(channel(), testOptions())`, where `testOptions()` builds an `MxGatewayClientOptions` with a dummy api-key.
|
||||
- `close()` shuts down channel + server.
|
||||
|
||||
**Step 2: Smoke-verify the harness in isolation** — add a temporary `@Test` (or a tiny self-test) that opens the harness, calls `gatewayClient()` and streams one scripted event, then delete it before commit. Build:
|
||||
`gradle :zb-mom-ww-mxgateway-cli:compileTestJava`.
|
||||
|
||||
**Step 3: Run the cli test set to confirm nothing breaks:**
|
||||
`gradle :zb-mom-ww-mxgateway-cli:test --tests '*MxGatewayCliTests'`.
|
||||
|
||||
**Step 4: Commit** `test(java-cli): add in-process gRPC harness fixture`.
|
||||
|
||||
**Acceptance:** Compiles; harness starts/stops cleanly; scripted services reachable through the real client types. (No assertions on CLI yet — that's Tasks 5–6.)
|
||||
|
||||
---
|
||||
|
||||
## Task 5: stream-events CLI test via harness
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** Task 7, 8, 9
|
||||
**blockedBy:** Task 2 (same test file ordering), Task 4 (harness)
|
||||
|
||||
**Files:**
|
||||
- Test: `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java`
|
||||
|
||||
**Step 1: Wire a harness-backed `MxGatewayCliClientFactory`** in the test that builds the CLI client over `harness.gatewayClient()` (reuse the production adapter that wraps `MxGatewayClient` as `MxGatewayCliClient`; it is package-visible from the test's package). Script ≥2 `MxEvent`s including one with a **high uint64 worker sequence** to cover the unsigned-format regression.
|
||||
|
||||
**Step 2: Write the failing test** `streamEventsRendersScriptedEventsIncludingHighUint64Sequence` — run `stream-events`, assert stdout contains the scripted event fields and the high sequence renders unsigned (not negative).
|
||||
|
||||
**Step 3: Run failing → (harness already supplies behavior) → PASS:**
|
||||
`gradle :zb-mom-ww-mxgateway-cli:test --tests '*MxGatewayCliTests'`.
|
||||
|
||||
**Step 4: Commit** `test(java-cli): cover stream-events over in-process harness`.
|
||||
|
||||
**Acceptance:** stream-events exercised through the real `MxEventStream`; unsigned-sequence rendering asserted.
|
||||
|
||||
---
|
||||
|
||||
## Task 6: galaxy-watch + galaxy-discover CLI tests via harness
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** Task 7, 8, 9
|
||||
**blockedBy:** Task 3 (GalaxyClientFactory seam), Task 5 (same test file ordering)
|
||||
|
||||
**Files:**
|
||||
- Test: `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java`
|
||||
|
||||
**Step 1: Wire a harness-backed `GalaxyClientFactory`** (from Task 3) that returns `harness.galaxyClient()`.
|
||||
|
||||
**Step 2: Write the failing tests:**
|
||||
- `galaxyDiscoverPrintsPagedHierarchyJson` — assert the scripted `GalaxyObject` hierarchy renders in CLI JSON (object fields + counts).
|
||||
- `galaxyWatchRendersScriptedDeployEvents` — assert the scripted deploy events render in the CLI feed; honor `--limit` if the command supports it.
|
||||
|
||||
**Step 3: Run failing → PASS:** `gradle :zb-mom-ww-mxgateway-cli:test --tests '*MxGatewayCliTests'`.
|
||||
|
||||
**Step 4: Full cli module verification** (this closes the §8 Java item): `gradle :zb-mom-ww-mxgateway-cli:test`.
|
||||
|
||||
**Step 5: Commit** `test(java-cli): cover galaxy-discover/galaxy-watch over in-process harness`.
|
||||
|
||||
**Acceptance:** All 10 previously-untested subcommands now have CLI coverage; `MxGatewayCliTests` green.
|
||||
|
||||
---
|
||||
|
||||
## Task 7: WorkerReadyWaitTimeoutMs option + validator + doc
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~4 min
|
||||
**Parallelizable with:** all Java tasks (1–6), Task 9
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Server/Configuration/SessionOptions.cs`
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayOptionsValidator.cs`
|
||||
- Modify: `docs/GatewayConfiguration.md`
|
||||
- Test: `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Configuration/GatewayOptionsTests.cs` (or the existing options-validator test class)
|
||||
|
||||
**Step 1: Add the option** to `SessionOptions` (match the `{ get; init; }` + XML-doc style):
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// Gets the bounded time, in milliseconds, the gateway will wait for a worker client
|
||||
/// to reach <c>Ready</c> when the session itself is already <c>Ready</c> but the worker
|
||||
/// state has transiently diverged (e.g. <c>Handshaking</c> after a heartbeat blip).
|
||||
/// The wait applies only to transient worker states; terminal states
|
||||
/// (<c>Faulted</c>/<c>Closing</c>/<c>Closed</c>/no worker) fail fast immediately.
|
||||
/// A value of <c>0</c> (the default) disables the wait — the gateway keeps the original
|
||||
/// fail-fast behavior. Must be greater than or equal to zero.
|
||||
/// </summary>
|
||||
public int WorkerReadyWaitTimeoutMs { get; init; }
|
||||
```
|
||||
|
||||
**Step 2: Validate `>= 0`** in `GatewayOptionsValidator` (mirror an existing numeric check; message e.g. `MxGateway:Sessions:WorkerReadyWaitTimeoutMs must be greater than or equal to zero.`).
|
||||
|
||||
**Step 3: Document** the new key in `docs/GatewayConfiguration.md` under the `MxGateway:Sessions` section (default 0 = disabled; transient-only; terminal fails fast).
|
||||
|
||||
**Step 4: Write + run the failing test** asserting default is `0` and a negative value fails validation:
|
||||
`dotnet test src/ZB.MOM.WW.MxGateway.Tests --filter "FullyQualifiedName~GatewayOptions"` → expect FAIL pre-impl, PASS post.
|
||||
|
||||
**Step 5: Commit** `feat(server): add MxGateway:Sessions:WorkerReadyWaitTimeoutMs (default off)`.
|
||||
|
||||
**Acceptance:** Option binds, default 0, negative rejected, doc updated.
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Bounded ready-wait in GatewaySession + tests
|
||||
|
||||
**Classification:** high-risk
|
||||
**Estimated implement time:** ~5 min (split if it grows)
|
||||
**Parallelizable with:** all Java tasks, Task 9
|
||||
**blockedBy:** Task 7
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Server/Sessions/GatewaySession.cs` (`GetReadyWorkerClient` `:1665`; `InvokeAsync` `:918`; `ReadEventsAsync` `:1263`)
|
||||
- Test: `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionManagerTests.cs` (or the test class covering `GetReadyWorkerClient` diagnostics)
|
||||
|
||||
**Context & constraints:** The not-ready check runs inside the `_syncRoot` lock — **never sleep/poll inside the lock**. Read state under the lock, release, await, re-check. The both-states diagnostic (`Session state is {_state}; worker state is {workerState}.`) MUST be preserved for the final failure. Default timeout 0 ⇒ behavior identical to today.
|
||||
|
||||
**Step 1: Write failing tests first (TDD)** in the session-manager test class, using a `FakeWorkerClient` whose `State` is settable:
|
||||
- `InvokeAsync_WhenWorkerHandshakingThenReadyWithinTimeout_Succeeds` — option `WorkerReadyWaitTimeoutMs=500`; worker starts `Handshaking`, flips to `Ready` after ~50 ms (e.g. via a background `Task` or a `TimeProvider`-driven advance); assert the invoke succeeds and the worker is invoked once.
|
||||
- `InvokeAsync_WhenWorkerFaulted_FailsFastWithBothStates` — worker `Faulted`, timeout 500; assert it throws *immediately* (no meaningful delay) and the message contains both `Session state is Ready` and `worker state is Faulted`.
|
||||
- `InvokeAsync_WhenTimeoutElapsesStillNotReady_FailsWithBothStates` — worker stays `Handshaking`, timeout small (e.g. 100 ms); assert throw after ~timeout with both states.
|
||||
- `InvokeAsync_WhenTimeoutZero_FailsFastUnchanged` — worker `Handshaking`, timeout 0; assert immediate fail-fast (pins the no-behavior-change default).
|
||||
|
||||
**Step 2: Run tests → expect FAIL/compile-error** (`GetReadyWorkerClientAsync` not present):
|
||||
`dotnet test src/ZB.MOM.WW.MxGateway.Tests --filter "FullyQualifiedName~SessionManager"`.
|
||||
|
||||
**Step 3: Implement `GetReadyWorkerClientAsync(CancellationToken)`:**
|
||||
- Under `_syncRoot`: capture `_state` and `_workerClient?.State`. If session is `Ready` and worker is `Ready` → return it (fast path, no await). If worker is terminal (`Faulted`/`Closing`/`Closed`) or null, or session not `Ready` → throw the both-states `SessionManagerException` now (fail fast). If worker is transient (`Handshaking`/`Created`) AND `WorkerReadyWaitTimeoutMs > 0` → fall through to the wait.
|
||||
- Wait loop OUTSIDE the lock: until a deadline (`now + WorkerReadyWaitTimeoutMs`), `await Task.Delay(pollIntervalMs, ct)` (const `pollIntervalMs = 25`), then re-acquire `_syncRoot` and re-evaluate: Ready → return; terminal/null/session-not-Ready → fail fast with both states; still transient → keep waiting. On deadline → throw both-states.
|
||||
- Keep the existing synchronous `GetReadyWorkerClient()` for any non-async caller, or have it delegate to a zero-wait evaluation to avoid duplicated message logic (extract a private `EvaluateReadyUnderLock(out string failureMessage)` helper used by both).
|
||||
|
||||
**Step 4: Update callers:**
|
||||
- `InvokeAsync` (`:918`): `IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false);`.
|
||||
- `ReadEventsAsync` (`:1263`): convert to an async iterator — `public async IAsyncEnumerable<WorkerEvent> ReadEventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)`, `await GetReadyWorkerClientAsync(...)`, `TouchClientActivity(...)`, then `await foreach (var e in workerClient.ReadEventsAsync(cancellationToken)) yield return e;`. Verify no caller relied on eager (pre-enumeration) throw semantics — if one does, note it for the reviewer.
|
||||
|
||||
**Step 5: Run the targeted tests → PASS** (same filter). Confirm the 4 new tests + pre-existing `GetReadyWorkerClient` diagnostic test all pass.
|
||||
|
||||
**Step 6: Commit** `feat(server): bounded worker-ready wait in GatewaySession (default off)`.
|
||||
|
||||
**Acceptance:** Transient states wait up to the timeout; terminal states fail fast with both states; default 0 is byte-for-byte the old behavior; no sleeping under `_syncRoot`.
|
||||
|
||||
---
|
||||
|
||||
## Task 9: FakeWorkerProcess consolidation
|
||||
|
||||
**Classification:** standard
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** all tasks
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs` (canonical — extend if needed)
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs` (nested copy ~line 343)
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs` (nested copy ~line 244)
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerClientTests.cs` (nested copy ~line 767; already `using ...TestSupport`)
|
||||
|
||||
**Context:** Canonical `TestSupport/FakeWorkerProcess(int)` has `MarkExited`/`Kill`/TCS-backed `WaitForExitAsync`. Three test files still declare private nested `FakeWorkerProcess`. Consolidate.
|
||||
|
||||
**Step 1: Diff each nested copy against the canonical.** For each, list any members/behavior the canonical lacks (e.g. extra counters, scripted exit codes). Fold those into the canonical `TestSupport/FakeWorkerProcess` **first** (additively, so existing canonical users keep compiling).
|
||||
|
||||
**Step 2: Delete each nested class** and update references to the canonical type; add/confirm `using ZB.MOM.WW.MxGateway.Tests.TestSupport;`.
|
||||
|
||||
**Step 3: Run the three affected test classes:**
|
||||
```
|
||||
dotnet test src/ZB.MOM.WW.MxGateway.Tests --filter "FullyQualifiedName~WorkerClientTests|FullyQualifiedName~WorkerProcessLauncherTests|FullyQualifiedName~SessionWorkerClientFactoryFakeWorkerTests"
|
||||
```
|
||||
Expected: all pass (behavior preserved; `KillCount`/`HasExited`/`ExitCode` semantics intact).
|
||||
|
||||
**Step 4: Commit** `refactor(tests): consolidate FakeWorkerProcess onto TestSupport canonical`.
|
||||
|
||||
**Acceptance:** Exactly one `FakeWorkerProcess` definition (the canonical); three files import it; affected tests green.
|
||||
|
||||
---
|
||||
|
||||
## Final verification (after Tasks 8 + 9)
|
||||
|
||||
Run the full gateway suite once to confirm no cross-cutting regression:
|
||||
```
|
||||
dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj
|
||||
```
|
||||
Expected baseline: prior green count + the new Task 7/8/9 tests; the 3 known macOS-environmental failures (TLS temp-file, OrphanWorkerTerminator ×2) may persist — confirm no *new* failures.
|
||||
|
||||
Then finish via `superpowers-extended-cc:finishing-a-development-branch`.
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"planPath": "docs/plans/2026-06-16-stillpending-section8.md",
|
||||
"tasks": [
|
||||
{"id": 140, "subject": "Task 1: FakeSession recorders + read/write/write2-bulk CLI tests", "status": "pending"},
|
||||
{"id": 141, "subject": "Task 2: secured/secured2/bench-bulk + close-session CLI tests", "status": "pending", "blockedBy": [140]},
|
||||
{"id": 142, "subject": "Task 3: GalaxyClientFactory seam + cli grpc test deps", "status": "pending"},
|
||||
{"id": 143, "subject": "Task 4: In-process gRPC harness fixture", "status": "pending"},
|
||||
{"id": 144, "subject": "Task 5: stream-events CLI test via harness", "status": "pending", "blockedBy": [141, 143]},
|
||||
{"id": 145, "subject": "Task 6: galaxy-watch + galaxy-discover CLI tests via harness", "status": "pending", "blockedBy": [142, 144]},
|
||||
{"id": 146, "subject": "Task 7: WorkerReadyWaitTimeoutMs option + validator + doc", "status": "pending"},
|
||||
{"id": 147, "subject": "Task 8: Bounded ready-wait in GatewaySession + tests", "status": "pending", "blockedBy": [146]},
|
||||
{"id": 148, "subject": "Task 9: FakeWorkerProcess consolidation", "status": "pending"}
|
||||
],
|
||||
"lastUpdated": "2026-06-16"
|
||||
}
|
||||
@@ -185,6 +185,10 @@ public sealed class GatewayOptionsValidator : OptionsValidatorBase<GatewayOption
|
||||
options.DetachGraceSeconds,
|
||||
"MxGateway:Sessions:DetachGraceSeconds must be zero or greater (0 disables detach-grace retention).",
|
||||
builder);
|
||||
AddIfNegative(
|
||||
options.WorkerReadyWaitTimeoutMs,
|
||||
"MxGateway:Sessions:WorkerReadyWaitTimeoutMs must be greater than or equal to zero.",
|
||||
builder);
|
||||
|
||||
// NOTE: We intentionally do NOT reject !AllowMultipleEventSubscribers &&
|
||||
// MaxEventSubscribersPerSession > 1 as a hard validation error here. The default
|
||||
|
||||
@@ -56,4 +56,15 @@ public sealed class SessionOptions
|
||||
/// effectively 1 when it is <see langword="false"/>. Must be greater than zero.
|
||||
/// </summary>
|
||||
public int MaxEventSubscribersPerSession { get; init; } = 8;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the bounded time, in milliseconds, the gateway will wait for a worker client
|
||||
/// to reach <c>Ready</c> when the session itself is already <c>Ready</c> but the worker
|
||||
/// state has transiently diverged (e.g. <c>Handshaking</c> after a heartbeat blip).
|
||||
/// The wait applies only to transient worker states; terminal states
|
||||
/// (<c>Faulted</c>/<c>Closing</c>/<c>Closed</c>/no worker) fail fast immediately.
|
||||
/// A value of <c>0</c> (the default) disables the wait — the gateway keeps the original
|
||||
/// fail-fast behavior. Must be greater than or equal to zero.
|
||||
/// </summary>
|
||||
public int WorkerReadyWaitTimeoutMs { get; init; }
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ public sealed class GatewaySession
|
||||
private bool _closeStarted;
|
||||
private int _activeEventSubscriberCount;
|
||||
private readonly TimeSpan _detachGrace;
|
||||
private readonly TimeSpan _workerReadyWaitTimeout;
|
||||
private DateTimeOffset? _detachedAtUtc;
|
||||
private SessionEventDistributor? _eventDistributor;
|
||||
private bool _eventDistributorStarted;
|
||||
@@ -115,6 +116,17 @@ public sealed class GatewaySession
|
||||
/// The clock comes from <paramref name="eventStreaming"/>'s
|
||||
/// <see cref="SessionEventStreaming.TimeProvider"/> so the timer is unit-testable.
|
||||
/// </param>
|
||||
/// <param name="workerReadyWaitTimeout">
|
||||
/// Bounded time the session will wait, on the command/event hot path, for the worker
|
||||
/// client to reach <see cref="WorkerClientState.Ready"/> when the session is already
|
||||
/// <see cref="SessionState.Ready"/> but the worker state has transiently diverged
|
||||
/// (e.g. <see cref="WorkerClientState.Handshaking"/> after a heartbeat blip). The wait
|
||||
/// applies only to transient worker states; terminal states
|
||||
/// (<see cref="WorkerClientState.Faulted"/>/<see cref="WorkerClientState.Closing"/>/
|
||||
/// <see cref="WorkerClientState.Closed"/>/no worker) and a non-<c>Ready</c> session fail
|
||||
/// fast immediately. <see cref="TimeSpan.Zero"/> (the default) disables the wait and
|
||||
/// preserves the original fail-fast behavior byte-for-byte.
|
||||
/// </param>
|
||||
public GatewaySession(
|
||||
string sessionId,
|
||||
string backendName,
|
||||
@@ -130,7 +142,8 @@ public sealed class GatewaySession
|
||||
TimeSpan leaseDuration,
|
||||
DateTimeOffset openedAt,
|
||||
SessionEventStreaming? eventStreaming = null,
|
||||
TimeSpan detachGrace = default)
|
||||
TimeSpan detachGrace = default,
|
||||
TimeSpan workerReadyWaitTimeout = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(sessionId))
|
||||
{
|
||||
@@ -169,6 +182,7 @@ public sealed class GatewaySession
|
||||
_leaseExpiresAt = openedAt + leaseDuration;
|
||||
_eventStreaming = eventStreaming ?? SessionEventStreaming.Default;
|
||||
_detachGrace = detachGrace > TimeSpan.Zero ? detachGrace : TimeSpan.Zero;
|
||||
_workerReadyWaitTimeout = workerReadyWaitTimeout > TimeSpan.Zero ? workerReadyWaitTimeout : TimeSpan.Zero;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -915,7 +929,7 @@ public sealed class GatewaySession
|
||||
WorkerCommand command,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
IWorkerClient workerClient = GetReadyWorkerClient();
|
||||
IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false);
|
||||
TouchClientActivity(_eventStreaming.TimeProvider.GetUtcNow());
|
||||
|
||||
return await workerClient.InvokeAsync(command, CommandTimeout, cancellationToken).ConfigureAwait(false);
|
||||
@@ -1258,12 +1272,20 @@ public sealed class GatewaySession
|
||||
/// Reads events from the worker as an asynchronous enumerable stream.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">Token to cancel the asynchronous operation.</param>
|
||||
public IAsyncEnumerable<WorkerEvent> ReadEventsAsync(CancellationToken cancellationToken)
|
||||
/// <returns>An asynchronous stream of worker events.</returns>
|
||||
public async IAsyncEnumerable<WorkerEvent> ReadEventsAsync(
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken)
|
||||
{
|
||||
IWorkerClient workerClient = GetReadyWorkerClient();
|
||||
IWorkerClient workerClient = await GetReadyWorkerClientAsync(cancellationToken).ConfigureAwait(false);
|
||||
TouchClientActivity(_eventStreaming.TimeProvider.GetUtcNow());
|
||||
|
||||
return workerClient.ReadEventsAsync(cancellationToken);
|
||||
await foreach (WorkerEvent workerEvent in workerClient
|
||||
.ReadEventsAsync(cancellationToken)
|
||||
.WithCancellation(cancellationToken)
|
||||
.ConfigureAwait(false))
|
||||
{
|
||||
yield return workerEvent;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -1650,34 +1672,136 @@ public sealed class GatewaySession
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the worker client iff both the gateway-side session state AND
|
||||
/// the worker client's own state are <see cref="SessionState.Ready"/> /
|
||||
/// <see cref="WorkerClientState.Ready"/>. The two states can diverge under
|
||||
/// load: <c>_state</c> only transitions on gateway-driven events (open,
|
||||
/// close, fault), while <see cref="WorkerClient.State"/> can shift on
|
||||
/// worker-side signals (heartbeat watchdog, pipe disconnect) before the
|
||||
/// gateway's session-level reaction observes them. When that happens the
|
||||
/// in-flight RPC fails fast here with both states surfaced in the
|
||||
/// diagnostic (Server-030) so the actual mismatch is actionable instead
|
||||
/// of misleading. The session usually transitions to <c>Faulted</c>
|
||||
/// shortly after.
|
||||
/// Bounded, opt-in async variant of the fail-fast readiness check. When the
|
||||
/// session is <see cref="SessionState.Ready"/> but the worker has transiently diverged
|
||||
/// to a non-terminal state (<see cref="WorkerClientState.Handshaking"/>/
|
||||
/// <see cref="WorkerClientState.Created"/>) and the configured worker-ready wait timeout
|
||||
/// is positive, this polls (outside <c>_syncRoot</c>) until the worker reaches
|
||||
/// <see cref="WorkerClientState.Ready"/> or the deadline elapses, re-evaluating the
|
||||
/// fast-path/fail-fast decision under the lock on each poll. Terminal worker states, a
|
||||
/// missing worker, or a non-<c>Ready</c> session fail fast immediately. With the default
|
||||
/// timeout of zero this behaves byte-for-byte like the synchronous fail-fast path: no
|
||||
/// await, no delay.
|
||||
/// </summary>
|
||||
private IWorkerClient GetReadyWorkerClient()
|
||||
/// <param name="cancellationToken">Token to cancel the wait.</param>
|
||||
/// <returns>The worker client once both the session and worker are <c>Ready</c>.</returns>
|
||||
private async Task<IWorkerClient> GetReadyWorkerClientAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
const int pollIntervalMs = 25;
|
||||
|
||||
string? failureMessage;
|
||||
lock (_syncRoot)
|
||||
{
|
||||
if (_state != SessionState.Ready || _workerClient?.State != WorkerClientState.Ready)
|
||||
IWorkerClient? ready = EvaluateReadyUnderLock(out failureMessage);
|
||||
if (ready is not null)
|
||||
{
|
||||
string workerState = _workerClient is null
|
||||
? "<no worker>"
|
||||
: _workerClient.State.ToString();
|
||||
throw new SessionManagerException(
|
||||
SessionManagerErrorCode.SessionNotReady,
|
||||
$"Session {SessionId} is not ready. Session state is {_state}; worker state is {workerState}.");
|
||||
return ready;
|
||||
}
|
||||
|
||||
// Only transient (non-terminal) worker states with a positive wait timeout fall
|
||||
// through to the bounded wait loop. Everything else (terminal worker, no worker,
|
||||
// session not Ready, or a zero timeout) fails fast right here under the lock. When
|
||||
// the worker is merely transient (failureMessage is null) but the wait is disabled,
|
||||
// build the both-states diagnostic so the zero-timeout path is byte-for-byte the
|
||||
// original fail-fast message.
|
||||
if (failureMessage is not null || _workerReadyWaitTimeout <= TimeSpan.Zero)
|
||||
{
|
||||
throw new SessionManagerException(
|
||||
SessionManagerErrorCode.SessionNotReady,
|
||||
failureMessage ?? BuildNotReadyMessage());
|
||||
}
|
||||
}
|
||||
|
||||
DateTimeOffset deadline = _eventStreaming.TimeProvider.GetUtcNow() + _workerReadyWaitTimeout;
|
||||
while (true)
|
||||
{
|
||||
await Task.Delay(
|
||||
TimeSpan.FromMilliseconds(pollIntervalMs),
|
||||
_eventStreaming.TimeProvider,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
lock (_syncRoot)
|
||||
{
|
||||
IWorkerClient? ready = EvaluateReadyUnderLock(out failureMessage);
|
||||
if (ready is not null)
|
||||
{
|
||||
return ready;
|
||||
}
|
||||
|
||||
// A terminal worker / missing worker / non-Ready session surfaced while we
|
||||
// waited: fail fast immediately rather than burning the rest of the deadline.
|
||||
if (failureMessage is not null)
|
||||
{
|
||||
throw new SessionManagerException(SessionManagerErrorCode.SessionNotReady, failureMessage);
|
||||
}
|
||||
}
|
||||
|
||||
if (_eventStreaming.TimeProvider.GetUtcNow() >= deadline)
|
||||
{
|
||||
lock (_syncRoot)
|
||||
{
|
||||
IWorkerClient? ready = EvaluateReadyUnderLock(out failureMessage);
|
||||
if (ready is not null)
|
||||
{
|
||||
return ready;
|
||||
}
|
||||
|
||||
throw new SessionManagerException(
|
||||
SessionManagerErrorCode.SessionNotReady,
|
||||
failureMessage ?? BuildNotReadyMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Evaluates readiness while the caller already holds <c>_syncRoot</c>. Returns the
|
||||
/// worker client when both the session and worker are <see cref="WorkerClientState.Ready"/>
|
||||
/// (with <paramref name="failureMessage"/> set to <see langword="null"/>). Returns
|
||||
/// <see langword="null"/> together with the both-states diagnostic in
|
||||
/// <paramref name="failureMessage"/> when the worker is in a terminal state
|
||||
/// (<see cref="WorkerClientState.Faulted"/>/<see cref="WorkerClientState.Closing"/>/
|
||||
/// <see cref="WorkerClientState.Closed"/>), there is no worker, or the session is not
|
||||
/// <see cref="SessionState.Ready"/>. Returns <see langword="null"/> with a
|
||||
/// <see langword="null"/> <paramref name="failureMessage"/> when the session is
|
||||
/// <c>Ready</c> but the worker is in a transient state
|
||||
/// (<see cref="WorkerClientState.Handshaking"/>/<see cref="WorkerClientState.Created"/>) —
|
||||
/// the signal for the async path to keep waiting.
|
||||
/// </summary>
|
||||
/// <param name="failureMessage">
|
||||
/// The fail-fast both-states diagnostic when readiness cannot succeed, or
|
||||
/// <see langword="null"/> for the keep-waiting (transient) signal.
|
||||
/// </param>
|
||||
/// <returns>The ready worker client, or <see langword="null"/>.</returns>
|
||||
private IWorkerClient? EvaluateReadyUnderLock(out string? failureMessage)
|
||||
{
|
||||
if (_state == SessionState.Ready && _workerClient?.State == WorkerClientState.Ready)
|
||||
{
|
||||
failureMessage = null;
|
||||
return _workerClient;
|
||||
}
|
||||
|
||||
// Keep-waiting signal: session is Ready and the worker is merely transient.
|
||||
if (_state == SessionState.Ready
|
||||
&& _workerClient is { State: WorkerClientState.Handshaking or WorkerClientState.Created })
|
||||
{
|
||||
failureMessage = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
failureMessage = BuildNotReadyMessage();
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Builds the both-states not-ready diagnostic (must be called under <c>_syncRoot</c>).</summary>
|
||||
/// <returns>The diagnostic message surfacing both the session and worker states.</returns>
|
||||
private string BuildNotReadyMessage()
|
||||
{
|
||||
string workerState = _workerClient is null
|
||||
? "<no worker>"
|
||||
: _workerClient.State.ToString();
|
||||
return $"Session {SessionId} is not ready. Session state is {_state}; worker state is {workerState}.";
|
||||
}
|
||||
|
||||
private void TrackItem(
|
||||
|
||||
@@ -505,7 +505,8 @@ public sealed class SessionManager : ISessionManager
|
||||
leaseDuration,
|
||||
openedAt,
|
||||
eventStreaming,
|
||||
TimeSpan.FromSeconds(Math.Max(0, _options.Sessions.DetachGraceSeconds)));
|
||||
TimeSpan.FromSeconds(Math.Max(0, _options.Sessions.DetachGraceSeconds)),
|
||||
TimeSpan.FromMilliseconds(Math.Max(0, _options.Sessions.WorkerReadyWaitTimeoutMs)));
|
||||
}
|
||||
|
||||
private static string CreateClientCorrelationId(
|
||||
|
||||
@@ -37,6 +37,7 @@ public sealed class GatewayOptionsTests
|
||||
Assert.Equal(30, options.Sessions.DetachGraceSeconds);
|
||||
Assert.False(options.Sessions.AllowMultipleEventSubscribers);
|
||||
Assert.Equal(8, options.Sessions.MaxEventSubscribersPerSession);
|
||||
Assert.Equal(0, options.Sessions.WorkerReadyWaitTimeoutMs);
|
||||
|
||||
Assert.Equal(10_000, options.Events.QueueCapacity);
|
||||
Assert.Equal(EventBackpressurePolicy.FailFast, options.Events.BackpressurePolicy);
|
||||
@@ -88,6 +89,7 @@ public sealed class GatewayOptionsTests
|
||||
[InlineData("MxGateway:Sessions:DefaultLeaseSeconds", "0", "MxGateway:Sessions:DefaultLeaseSeconds must be greater than zero.")]
|
||||
[InlineData("MxGateway:Sessions:LeaseSweepIntervalSeconds", "0", "MxGateway:Sessions:LeaseSweepIntervalSeconds must be greater than zero.")]
|
||||
[InlineData("MxGateway:Sessions:DetachGraceSeconds", "-1", "MxGateway:Sessions:DetachGraceSeconds must be zero or greater (0 disables detach-grace retention).")]
|
||||
[InlineData("MxGateway:Sessions:WorkerReadyWaitTimeoutMs", "-1", "MxGateway:Sessions:WorkerReadyWaitTimeoutMs must be greater than or equal to zero.")]
|
||||
[InlineData("MxGateway:Events:QueueCapacity", "0", "MxGateway:Events:QueueCapacity must be greater than zero.")]
|
||||
[InlineData("MxGateway:Protocol:MaxGrpcMessageBytes", "0", "MxGateway:Protocol:MaxGrpcMessageBytes must be between")]
|
||||
[InlineData("MxGateway:Authentication:PepperSecretName", "", "MxGateway:Authentication:PepperSecretName is required")]
|
||||
|
||||
@@ -356,4 +356,41 @@ public sealed class GatewayOptionsValidatorTests
|
||||
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// WorkerReadyWaitTimeoutMs validation
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
[Fact]
|
||||
public void Validate_Fails_WhenWorkerReadyWaitTimeoutMsIsNegative()
|
||||
{
|
||||
GatewayOptions options = CloneWithSessions(
|
||||
ValidOptions(),
|
||||
new SessionOptions { WorkerReadyWaitTimeoutMs = -1 });
|
||||
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
|
||||
Assert.True(result.Failed);
|
||||
Assert.Contains(
|
||||
result.Failures!,
|
||||
f => f.Contains("MxGateway:Sessions:WorkerReadyWaitTimeoutMs"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Succeeds_WhenWorkerReadyWaitTimeoutMsIsZero()
|
||||
{
|
||||
GatewayOptions options = CloneWithSessions(
|
||||
ValidOptions(),
|
||||
new SessionOptions { WorkerReadyWaitTimeoutMs = 0 });
|
||||
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_Succeeds_WhenWorkerReadyWaitTimeoutMsIsPositive()
|
||||
{
|
||||
GatewayOptions options = CloneWithSessions(
|
||||
ValidOptions(),
|
||||
new SessionOptions { WorkerReadyWaitTimeoutMs = 5000 });
|
||||
ValidateOptionsResult result = new GatewayOptionsValidator().Validate(null, options);
|
||||
Assert.True(result.Succeeded);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
@@ -366,6 +367,124 @@ public sealed class SessionManagerTests
|
||||
Assert.Equal(0, workerClient.InvokeCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// With the opt-in worker-ready wait enabled, a worker that is transiently
|
||||
/// <c>Handshaking</c> but flips to <c>Ready</c> within the timeout window must let the
|
||||
/// command through rather than fail fast.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenWorkerHandshakingThenReadyWithinTimeout_Succeeds()
|
||||
{
|
||||
FakeWorkerClient workerClient = new() { State = WorkerClientState.Handshaking };
|
||||
SessionManager manager = CreateManager(
|
||||
new FakeSessionWorkerClientFactory(workerClient),
|
||||
options: CreateOptions(workerReadyWaitTimeoutMs: 500));
|
||||
GatewaySession session = await manager.OpenSessionAsync(CreateOpenRequest(), "client-1", ownerKeyId: null, CancellationToken.None);
|
||||
Assert.Equal(SessionState.Ready, session.State);
|
||||
|
||||
// Flip the worker to Ready shortly after the invoke starts waiting.
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(50, CancellationToken.None);
|
||||
workerClient.State = WorkerClientState.Ready;
|
||||
});
|
||||
|
||||
WorkerCommandReply reply = await manager.InvokeAsync(
|
||||
session.SessionId,
|
||||
CreateCommand(MxCommandKind.Ping),
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.NotNull(reply);
|
||||
Assert.Equal(1, workerClient.InvokeCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A terminal worker state (<c>Faulted</c>) must fail fast even with a positive
|
||||
/// worker-ready wait timeout, surfacing both states without burning the timeout.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenWorkerFaulted_FailsFastWithBothStates()
|
||||
{
|
||||
FakeWorkerClient workerClient = new() { State = WorkerClientState.Faulted };
|
||||
SessionManager manager = CreateManager(
|
||||
new FakeSessionWorkerClientFactory(workerClient),
|
||||
options: CreateOptions(workerReadyWaitTimeoutMs: 500));
|
||||
GatewaySession session = await manager.OpenSessionAsync(CreateOpenRequest(), "client-1", ownerKeyId: null, CancellationToken.None);
|
||||
Assert.Equal(SessionState.Ready, session.State);
|
||||
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
SessionManagerException exception = await Assert.ThrowsAsync<SessionManagerException>(
|
||||
async () => await manager.InvokeAsync(
|
||||
session.SessionId,
|
||||
CreateCommand(MxCommandKind.Ping),
|
||||
CancellationToken.None));
|
||||
stopwatch.Stop();
|
||||
|
||||
Assert.True(stopwatch.ElapsedMilliseconds < 100, $"Expected immediate fail-fast but took {stopwatch.ElapsedMilliseconds}ms.");
|
||||
Assert.Equal(SessionManagerErrorCode.SessionNotReady, exception.ErrorCode);
|
||||
Assert.Contains("Session state is Ready", exception.Message);
|
||||
Assert.Contains("worker state is Faulted", exception.Message);
|
||||
Assert.Equal(0, workerClient.InvokeCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// When the worker stays transiently not-ready for the whole (small) timeout window,
|
||||
/// the invoke fails after roughly the timeout with both states surfaced.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenTimeoutElapsesStillNotReady_FailsWithBothStates()
|
||||
{
|
||||
FakeWorkerClient workerClient = new() { State = WorkerClientState.Handshaking };
|
||||
SessionManager manager = CreateManager(
|
||||
new FakeSessionWorkerClientFactory(workerClient),
|
||||
options: CreateOptions(workerReadyWaitTimeoutMs: 100));
|
||||
GatewaySession session = await manager.OpenSessionAsync(CreateOpenRequest(), "client-1", ownerKeyId: null, CancellationToken.None);
|
||||
Assert.Equal(SessionState.Ready, session.State);
|
||||
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
SessionManagerException exception = await Assert.ThrowsAsync<SessionManagerException>(
|
||||
async () => await manager.InvokeAsync(
|
||||
session.SessionId,
|
||||
CreateCommand(MxCommandKind.Ping),
|
||||
CancellationToken.None));
|
||||
stopwatch.Stop();
|
||||
|
||||
Assert.True(stopwatch.ElapsedMilliseconds >= 90, $"Expected the wait to span the timeout but took only {stopwatch.ElapsedMilliseconds}ms.");
|
||||
Assert.Equal(SessionManagerErrorCode.SessionNotReady, exception.ErrorCode);
|
||||
Assert.Contains("Session state is Ready", exception.Message);
|
||||
Assert.Contains("worker state is Handshaking", exception.Message);
|
||||
Assert.Equal(0, workerClient.InvokeCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pins the default (timeout == 0) behavior: a transiently <c>Handshaking</c> worker
|
||||
/// fails fast immediately, byte-for-byte like the original fail-fast path.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task InvokeAsync_WhenTimeoutZero_FailsFastUnchanged()
|
||||
{
|
||||
FakeWorkerClient workerClient = new() { State = WorkerClientState.Handshaking };
|
||||
SessionManager manager = CreateManager(
|
||||
new FakeSessionWorkerClientFactory(workerClient),
|
||||
options: CreateOptions(workerReadyWaitTimeoutMs: 0));
|
||||
GatewaySession session = await manager.OpenSessionAsync(CreateOpenRequest(), "client-1", ownerKeyId: null, CancellationToken.None);
|
||||
Assert.Equal(SessionState.Ready, session.State);
|
||||
|
||||
Stopwatch stopwatch = Stopwatch.StartNew();
|
||||
SessionManagerException exception = await Assert.ThrowsAsync<SessionManagerException>(
|
||||
async () => await manager.InvokeAsync(
|
||||
session.SessionId,
|
||||
CreateCommand(MxCommandKind.Ping),
|
||||
CancellationToken.None));
|
||||
stopwatch.Stop();
|
||||
|
||||
Assert.True(stopwatch.ElapsedMilliseconds < 100, $"Expected immediate fail-fast but took {stopwatch.ElapsedMilliseconds}ms.");
|
||||
Assert.Equal(SessionManagerErrorCode.SessionNotReady, exception.ErrorCode);
|
||||
Assert.Contains("Session state is Ready", exception.Message);
|
||||
Assert.Contains("worker state is Handshaking", exception.Message);
|
||||
Assert.Equal(0, workerClient.InvokeCount);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that closing a session removes it from the registry.</summary>
|
||||
[Fact]
|
||||
public async Task CloseSessionAsync_RemovesClosedSession()
|
||||
@@ -876,7 +995,8 @@ public sealed class SessionManagerTests
|
||||
private static GatewayOptions CreateOptions(
|
||||
int maxSessions = 64,
|
||||
int defaultLeaseSeconds = 1800,
|
||||
int detachGraceSeconds = 0)
|
||||
int detachGraceSeconds = 0,
|
||||
int workerReadyWaitTimeoutMs = 0)
|
||||
{
|
||||
return new GatewayOptions
|
||||
{
|
||||
@@ -886,6 +1006,7 @@ public sealed class SessionManagerTests
|
||||
MaxSessions = maxSessions,
|
||||
DefaultLeaseSeconds = defaultLeaseSeconds,
|
||||
DetachGraceSeconds = detachGraceSeconds,
|
||||
WorkerReadyWaitTimeoutMs = workerReadyWaitTimeoutMs,
|
||||
},
|
||||
Worker = new WorkerOptions
|
||||
{
|
||||
|
||||
+1
-58
@@ -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
|
||||
|
||||
+6
-4
@@ -143,10 +143,12 @@ No placeholder/empty/`Assert.True(true)` tests were found anywhere.
|
||||
|
||||
## 8. Deferred test-coverage follow-ups (noted in resolutions, never filed as findings)
|
||||
|
||||
- **Java CLI bulk-subcommand coverage** — 6 of 13 non-trivial subcommands untested: `read-bulk`, `write-bulk`, `write2-bulk`, `write-secured-bulk`, `write-secured2-bulk`, `bench-read-bulk` (plus `stream-events`, the four `galaxy-*`, `close-session`). `code-reviews/Client.Java/findings.md:495` (Client.Java-026).
|
||||
- **Per-session-ACL TODO** at `Server/Dashboard/Hubs/EventsHub.cs` (`code-reviews/Server/findings.md:765`) — now scheduled as session-resilience epic Phase 4 (Tasks 16–19); not yet started.
|
||||
- **Worker-Ready retry race** noted at `code-reviews/Server/findings.md:611`.
|
||||
- **Duplicated `FakeWorkerProcess` harness** flagged as a latent regression vector — `code-reviews/Tests/findings.md:463`.
|
||||
> **Resolution update (2026-06-16, branch `feat/stillpending-section8`):** Three of the four items below are **Resolved** per `docs/plans/2026-06-16-stillpending-section8.md` (Java CLI coverage, Worker-Ready wait, duplicated `FakeWorkerProcess`). Java work verified on the windev toolchain (full cli suite green); C# verified locally. The remaining item (per-session-ACL TODO) was correctly out of scope — it is session-resilience epic Phase 4.
|
||||
|
||||
- ✅ **Java CLI bulk-subcommand coverage — RESOLVED.** All 10 previously-untested subcommands now have CLI-layer round-trip tests in `clients/java/zb-mom-ww-mxgateway-cli/src/test/java/com/zb/mom/ww/mxgateway/cli/MxGatewayCliTests.java`: the bulk family (`read-bulk`, `write-bulk`, `write2-bulk`, `write-secured-bulk`, `write-secured2-bulk`, `bench-read-bulk`) + `close-session` via the `FakeSession` seam; `stream-events`, `galaxy-discover`, `galaxy-watch` via a new in-process gRPC harness (`InProcessGatewayHarness`) that drives the real client over an in-process channel. A `GalaxyClientFactory` seam was added to `MxGatewayCli` (behavior-preserving default) to make the galaxy commands testable. Was: `code-reviews/Client.Java/findings.md:495` (Client.Java-026).
|
||||
- 🟡 **Per-session-ACL TODO** at `Server/Dashboard/Hubs/EventsHub.cs` (`code-reviews/Server/findings.md:765`) — still scheduled as session-resilience epic Phase 4 (Tasks 16–19); not yet started. (Out of scope for the §8 completion branch.)
|
||||
- ✅ **Worker-Ready retry race — RESOLVED.** `GatewaySession.GetReadyWorkerClient` is now an opt-in bounded ready-wait (`GetReadyWorkerClientAsync` + `MxGateway:Sessions:WorkerReadyWaitTimeoutMs`, **default `0` = unchanged fail-fast**): a session that is `Ready` while its worker is transiently `Handshaking`/`Created` waits up to the configured window for `Ready`; terminal worker states fail fast immediately with the both-states diagnostic preserved. Was: `code-reviews/Server/findings.md:611`.
|
||||
- ✅ **Duplicated `FakeWorkerProcess` harness — RESOLVED.** The three private nested `FakeWorkerProcess` copies were consolidated onto the canonical `src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs` (one definition remains). Was a latent regression vector — `code-reviews/Tests/findings.md:463`.
|
||||
|
||||
---
|
||||
|
||||
|
||||
Reference in New Issue
Block a user