From fafd79fa126a5572b663c06f9a8d3aace4ca7df5 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:44:43 -0500 Subject: [PATCH] fix(client-java): keepalive 30s/10s, close() cancels streams, typed stream errors, malformed-reply checks, lenient TLS for Galaxy client (CJV-001..007, #257) --- clients/java/README.md | 29 +- .../mxgateway/client/DeployEventStream.java | 8 + .../client/GalaxyRepositoryClient.java | 49 ++- .../ww/mxgateway/client/MxEventStream.java | 7 + .../mxgateway/client/MxGatewayChannels.java | 69 +++++ .../ww/mxgateway/client/MxGatewayClient.java | 58 ++-- .../client/MxGatewayClientOptions.java | 105 +++++++ .../ww/mxgateway/client/MxGatewaySession.java | 74 ++++- .../mxgateway/client/MxEventStreamTests.java | 2 +- .../client/MxGatewayClientHardeningTests.java | 283 ++++++++++++++++++ .../client/MxGatewayClientTlsTests.java | 33 ++ 11 files changed, 635 insertions(+), 82 deletions(-) create mode 100644 clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayChannels.java create mode 100644 clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientHardeningTests.java diff --git a/clients/java/README.md b/clients/java/README.md index ce6336c7..3e504bb6 100644 --- a/clients/java/README.md +++ b/clients/java/README.md @@ -79,6 +79,29 @@ only stops the client from waiting; it does not abort an in-flight MXAccess COM call on the worker STA. It is a **single-consumer** surface: drive `hasNext()`/`next()` (or `nextItem()`) from one thread only. +### Keepalive and closing + +The Netty channel sends an HTTP/2 PING every 30 s, waits 10 s for the +acknowledgement, and pings even while no call is active (`keepAliveTime`, +`keepAliveTimeout`, `keepAliveWithoutCalls(true)`). A half-open connection +(firewall idle-out, host power loss) therefore fails a deadline-less +`streamEvents()` reader with an exception within about 40 s instead of blocking +forever. Tune them on `MxGatewayClientOptions.builder()` or call +`disableKeepAlive()`. Keep `keepAliveTime` at or above the gateway's permitted +client ping interval (`MxGateway:*` keepalive policy, 30 s by default); pinging +faster makes the gateway send GOAWAY (`too_many_pings`). + +`close()` (and so try-with-resources) calls `shutdownNow()` on a channel the +client owns and waits up to 5 s for it to terminate: open streams are cancelled +and any thread blocked in `hasNext()` is woken with an exception. +`closeAndAwaitTermination()` is the graceful variant that lets in-flight calls +finish first (up to the connect timeout) before forcing shutdown. + +A command reply that is `OK` but lacks the expected payload (`register`, +`addItem`, `addItem2`, the bulk helpers, `readBulk`, `drainEvents`) throws +`MxGatewayMalformedReplyException` instead of returning handle `0` or an empty +list. + ### Event buffer, overflow, and interrupts The iterator buffers events in a bounded queue whose size is @@ -88,7 +111,11 @@ than `n` events behind, the client cancels the call, keeps the events already buffered, and throws `MxGatewayException` only after you have drained them. Resume with `streamEventsAfter(lastSeenWorkerSequence)`. If the consuming thread is interrupted, the call is cancelled, the interrupt flag is restored, and the -iterator throws a `CANCELLED` `StatusRuntimeException`. +iterator throws a `CANCELLED` `MxGatewayException` (cause: the +`StatusRuntimeException`). Stream failures go through the same typed mapping as +unary calls: `PERMISSION_DENIED` becomes `MxGatewayAuthorizationException`, +`UNAUTHENTICATED` becomes `MxGatewayAuthenticationException`, and the rest become +`MxGatewayException`, with credentials redacted from the description. `streamEventsAsync(request, StreamObserver)` is the non-dropping alternative: it delivers each event to your observer on the gRPC thread with no diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/DeployEventStream.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/DeployEventStream.java index b0e38944..b45498d6 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/DeployEventStream.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/DeployEventStream.java @@ -70,6 +70,10 @@ public final class DeployEventStream implements Iterator, AutoClose if (next == null) { next = take(); } + if (next instanceof StatusRuntimeException statusError) { + next = END; + throw MxGatewayErrors.fromGrpc("watch deploy events", statusError); + } if (next instanceof RuntimeException runtimeException) { next = END; throw runtimeException; @@ -108,6 +112,10 @@ public final class DeployEventStream implements Iterator, AutoClose return queue.take(); } catch (InterruptedException error) { Thread.currentThread().interrupt(); + ClientCallStreamObserver stream = requestStream; + if (stream != null) { + stream.cancel("interrupted while reading deploy events", error); + } return new StatusRuntimeException( Status.CANCELLED.withDescription("interrupted while reading deploy events")); } diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/GalaxyRepositoryClient.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/GalaxyRepositoryClient.java index e46a8296..08067d94 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/GalaxyRepositoryClient.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/GalaxyRepositoryClient.java @@ -19,8 +19,6 @@ import com.google.protobuf.Timestamp; import io.grpc.Channel; import io.grpc.ClientInterceptors; import io.grpc.ManagedChannel; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.stub.StreamObserver; import java.time.Instant; import java.util.Iterator; @@ -29,7 +27,6 @@ import java.util.Objects; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLException; /** * Thin wrapper around the generated {@link GalaxyRepositoryGrpc} stubs that @@ -41,6 +38,8 @@ public final class GalaxyRepositoryClient implements AutoCloseable { private static final int DISCOVER_HIERARCHY_PAGE_SIZE = 5000; private static final int BROWSE_CHILDREN_PAGE_SIZE = 500; + private static final long CLOSE_AWAIT_MILLIS = 5_000; + private final ManagedChannel ownedChannel; private final MxGatewayClientOptions options; private final GalaxyRepositoryGrpc.GalaxyRepositoryBlockingStub blockingStub; @@ -371,10 +370,25 @@ public final class GalaxyRepositoryClient implements AutoCloseable { return stub.withDeadlineAfter(options.streamTimeout().toNanos(), TimeUnit.NANOSECONDS); } + /** + * Closes the owned channel immediately: in-flight calls and open streams are + * cancelled (their readers see a transport error) and the call waits briefly + * for the channel to terminate. A graceful {@code shutdown()} would leave a + * deadline-less stream running forever, keeping the channel's threads and the + * gateway-side subscriber slot alive. Use {@link #closeAndAwaitTermination()} + * to let in-flight calls finish first. No-op for clients that do not own + * their channel. + */ @Override public void close() { - if (ownedChannel != null) { - ownedChannel.shutdown(); + if (ownedChannel == null) { + return; + } + ownedChannel.shutdownNow(); + try { + ownedChannel.awaitTermination(CLOSE_AWAIT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); } } @@ -403,30 +417,7 @@ public final class GalaxyRepositoryClient implements AutoCloseable { } private static ManagedChannel createChannel(MxGatewayClientOptions options) { - NettyChannelBuilder builder = NettyChannelBuilder.forTarget(options.endpoint()) - .maxInboundMessageSize(options.maxGrpcMessageBytes()); - if (!options.connectTimeout().isNegative()) { - builder.withOption( - io.grpc.netty.shaded.io.netty.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS, - Math.toIntExact(options.connectTimeout().toMillis())); - } - if (options.plaintext()) { - builder.usePlaintext(); - } else if (options.caCertificatePath() != null) { - try { - builder.sslContext(GrpcSslContexts.forClient() - .trustManager(options.caCertificatePath().toFile()) - .build()); - } catch (SSLException error) { - throw new MxGatewayException("failed to configure galaxy repository TLS", error); - } - } else { - builder.useTransportSecurity(); - } - if (!options.serverNameOverride().isBlank()) { - builder.overrideAuthority(options.serverNameOverride()); - } - return builder.build(); + return MxGatewayChannels.create(options); } private > T withDeadline(T stub) { diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxEventStream.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxEventStream.java index 26d1a4f6..acf82c9e 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxEventStream.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxEventStream.java @@ -97,6 +97,13 @@ public final class MxEventStream implements Iterator, AutoCloseable { if (next == null) { next = take(); } + if (next instanceof StatusRuntimeException statusError) { + // Typed mapping (authentication / authorization / redaction) like every + // unary path; the local-interrupt case arrives here as CANCELLED too and + // is distinguished by its description. + next = END; + throw MxGatewayErrors.fromGrpc("stream events", statusError); + } if (next instanceof RuntimeException runtimeException) { next = END; throw runtimeException; diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayChannels.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayChannels.java new file mode 100644 index 00000000..81268753 --- /dev/null +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayChannels.java @@ -0,0 +1,69 @@ +package com.zb.mom.ww.mxgateway.client; + +import io.grpc.ManagedChannel; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; + +/** + * Builds the Netty channel shared by {@link MxGatewayClient} and + * {@link GalaxyRepositoryClient} so both honour the same transport-security + * contract (plaintext, pinned CA, lenient self-signed default, strict + * verification) and the same HTTP/2 keepalive policy. + */ +final class MxGatewayChannels { + private MxGatewayChannels() { + } + + static ManagedChannel create(MxGatewayClientOptions options) { + NettyChannelBuilder builder = NettyChannelBuilder.forTarget(options.endpoint()) + .maxInboundMessageSize(options.maxGrpcMessageBytes()); + if (!options.connectTimeout().isNegative()) { + builder.withOption( + io.grpc.netty.shaded.io.netty.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS, + Math.toIntExact(options.connectTimeout().toMillis())); + } + applyKeepAlive(builder, options); + if (options.plaintext()) { + builder.usePlaintext(); + } else if (options.caCertificatePath() != null) { + try { + builder.sslContext(GrpcSslContexts.forClient() + .trustManager(options.caCertificatePath().toFile()) + .build()); + } catch (SSLException error) { + throw new MxGatewayException("failed to configure gateway TLS", error); + } + } else if (!options.requireCertificateValidation()) { + try { + builder.sslContext(GrpcSslContexts.forClient() + .trustManager(io.grpc.netty.shaded.io.netty.handler.ssl.util + .InsecureTrustManagerFactory.INSTANCE) + .build()); + } catch (SSLException error) { + throw new MxGatewayException("failed to configure lenient gateway TLS", error); + } + } else { + builder.useTransportSecurity(); + } + if (!options.serverNameOverride().isBlank()) { + builder.overrideAuthority(options.serverNameOverride()); + } + return builder.build(); + } + + /** + * Applies the HTTP/2 keepalive policy. Without it a half-open connection + * (firewall idle-out, host power loss) leaves deadline-less streams blocked + * forever. A {@code null} interval disables keepalive. + */ + private static void applyKeepAlive(NettyChannelBuilder builder, MxGatewayClientOptions options) { + if (options.keepAliveTime() == null) { + return; + } + builder.keepAliveTime(options.keepAliveTime().toNanos(), TimeUnit.NANOSECONDS) + .keepAliveTimeout(options.keepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS) + .keepAliveWithoutCalls(options.keepAliveWithoutCalls()); + } +} diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClient.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClient.java index 024fead3..cec4deec 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClient.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClient.java @@ -7,13 +7,10 @@ import com.google.protobuf.Duration; import io.grpc.Channel; import io.grpc.ClientInterceptors; import io.grpc.ManagedChannel; -import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; import io.grpc.stub.StreamObserver; import java.util.Objects; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLException; import mxaccess_gateway.v1.MxAccessGatewayGrpc; import mxaccess_gateway.v1.MxaccessGateway.AcknowledgeAlarmReply; import mxaccess_gateway.v1.MxaccessGateway.AcknowledgeAlarmRequest; @@ -41,6 +38,8 @@ import mxaccess_gateway.v1.MxaccessGateway.StreamEventsRequest; * status failures into typed {@link MxGatewayException} subclasses. */ public final class MxGatewayClient implements AutoCloseable { + private static final long CLOSE_AWAIT_MILLIS = 5_000; + private final ManagedChannel ownedChannel; private final MxGatewayClientOptions options; private final MxAccessGatewayGrpc.MxAccessGatewayBlockingStub blockingStub; @@ -366,10 +365,25 @@ public final class MxGatewayClient implements AutoCloseable { return subscription; } + /** + * Closes the owned channel immediately: in-flight calls and open streams are + * cancelled (their readers see a transport error) and the call waits briefly + * for the channel to terminate. A graceful {@code shutdown()} would leave a + * deadline-less stream running forever, keeping the channel's threads and the + * gateway-side subscriber slot alive. Use {@link #closeAndAwaitTermination()} + * to let in-flight calls finish first. No-op for clients that do not own + * their channel. + */ @Override public void close() { - if (ownedChannel != null) { - ownedChannel.shutdown(); + if (ownedChannel == null) { + return; + } + ownedChannel.shutdownNow(); + try { + ownedChannel.awaitTermination(CLOSE_AWAIT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); } } @@ -390,39 +404,7 @@ public final class MxGatewayClient implements AutoCloseable { } private static ManagedChannel createChannel(MxGatewayClientOptions options) { - NettyChannelBuilder builder = NettyChannelBuilder.forTarget(options.endpoint()) - .maxInboundMessageSize(options.maxGrpcMessageBytes()); - if (!options.connectTimeout().isNegative()) { - builder.withOption( - io.grpc.netty.shaded.io.netty.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS, - Math.toIntExact(options.connectTimeout().toMillis())); - } - if (options.plaintext()) { - builder.usePlaintext(); - } else if (options.caCertificatePath() != null) { - try { - builder.sslContext(GrpcSslContexts.forClient() - .trustManager(options.caCertificatePath().toFile()) - .build()); - } catch (SSLException error) { - throw new MxGatewayException("failed to configure gateway TLS", error); - } - } else if (!options.requireCertificateValidation()) { - try { - builder.sslContext(GrpcSslContexts.forClient() - .trustManager(io.grpc.netty.shaded.io.netty.handler.ssl.util - .InsecureTrustManagerFactory.INSTANCE) - .build()); - } catch (SSLException error) { - throw new MxGatewayException("failed to configure lenient gateway TLS", error); - } - } else { - builder.useTransportSecurity(); - } - if (!options.serverNameOverride().isBlank()) { - builder.overrideAuthority(options.serverNameOverride()); - } - return builder.build(); + return MxGatewayChannels.create(options); } /** diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientOptions.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientOptions.java index e5a89986..c107a681 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientOptions.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientOptions.java @@ -14,6 +14,10 @@ import java.util.Objects; public final class MxGatewayClientOptions { private static final Duration DEFAULT_CONNECT_TIMEOUT = Duration.ofSeconds(10); private static final Duration DEFAULT_CALL_TIMEOUT = Duration.ofSeconds(30); + /** Default HTTP/2 keepalive ping interval; matches the gateway's permitted client ping rate. */ + static final Duration DEFAULT_KEEP_ALIVE_TIME = Duration.ofSeconds(30); + /** Default time to wait for a keepalive ping acknowledgement. */ + static final Duration DEFAULT_KEEP_ALIVE_TIMEOUT = Duration.ofSeconds(10); private static final int DEFAULT_MAX_GRPC_MESSAGE_BYTES = 16 * 1024 * 1024; /** Default {@code StreamEvents} iterator buffer; sized to absorb bursts without dropping a slow consumer. */ static final int DEFAULT_EVENT_QUEUE_CAPACITY = 1024; @@ -29,6 +33,9 @@ public final class MxGatewayClientOptions { private final Duration streamTimeout; private final int maxGrpcMessageBytes; private final int eventQueueCapacity; + private final Duration keepAliveTime; + private final Duration keepAliveTimeout; + private final boolean keepAliveWithoutCalls; private MxGatewayClientOptions(Builder builder) { endpoint = requireText(builder.endpoint, "endpoint"); @@ -47,6 +54,9 @@ public final class MxGatewayClientOptions { throw new IllegalArgumentException("eventQueueCapacity must be positive"); } eventQueueCapacity = builder.eventQueueCapacity; + keepAliveTime = builder.keepAliveDisabled ? null : builder.keepAliveTime; + keepAliveTimeout = builder.keepAliveTimeout; + keepAliveWithoutCalls = builder.keepAliveWithoutCalls; } /** @@ -167,6 +177,37 @@ public final class MxGatewayClientOptions { return eventQueueCapacity; } + /** + * Returns the HTTP/2 keepalive ping interval, or {@code null} when keepalive + * is disabled. Default 30 s. Keepalive turns a half-open connection into a + * transport error instead of an indefinite hang on a deadline-less stream. + * + * @return the ping interval, or {@code null} + */ + public Duration keepAliveTime() { + return keepAliveTime; + } + + /** + * Returns how long to wait for a keepalive ping acknowledgement before the + * connection is closed (default 10 s). + * + * @return the keepalive timeout + */ + public Duration keepAliveTimeout() { + return keepAliveTimeout; + } + + /** + * Returns whether keepalive pings are sent while no call is active + * (default {@code true}). + * + * @return {@code true} if pings are sent on an idle channel + */ + public boolean keepAliveWithoutCalls() { + return keepAliveWithoutCalls; + } + @Override public String toString() { return "MxGatewayClientOptions{" @@ -193,6 +234,12 @@ public final class MxGatewayClientOptions { + streamTimeout + ", maxGrpcMessageBytes=" + maxGrpcMessageBytes + + ", keepAliveTime=" + + keepAliveTime + + ", keepAliveTimeout=" + + keepAliveTimeout + + ", keepAliveWithoutCalls=" + + keepAliveWithoutCalls + '}'; } @@ -218,6 +265,10 @@ public final class MxGatewayClientOptions { private Duration streamTimeout; private int maxGrpcMessageBytes; private int eventQueueCapacity = DEFAULT_EVENT_QUEUE_CAPACITY; + private Duration keepAliveTime = DEFAULT_KEEP_ALIVE_TIME; + private Duration keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT; + private boolean keepAliveWithoutCalls = true; + private boolean keepAliveDisabled; private Builder() { } @@ -344,6 +395,60 @@ public final class MxGatewayClientOptions { return this; } + /** + * Sets the HTTP/2 keepalive ping interval (default 30 s). Keep it at or + * above the gateway's permitted client ping interval (30 s by default) or + * the gateway answers with GOAWAY ({@code too_many_pings}). + * + * @param value the ping interval, must be positive + * @return this builder + */ + public Builder keepAliveTime(Duration value) { + Objects.requireNonNull(value, "keepAliveTime"); + if (value.isZero() || value.isNegative()) { + throw new IllegalArgumentException("keepAliveTime must be positive"); + } + keepAliveTime = value; + keepAliveDisabled = false; + return this; + } + + /** + * Sets how long to wait for a keepalive ping acknowledgement (default 10 s). + * + * @param value the timeout, must be positive + * @return this builder + */ + public Builder keepAliveTimeout(Duration value) { + Objects.requireNonNull(value, "keepAliveTimeout"); + if (value.isZero() || value.isNegative()) { + throw new IllegalArgumentException("keepAliveTimeout must be positive"); + } + keepAliveTimeout = value; + return this; + } + + /** + * Sets whether keepalive pings are sent while no call is active (default {@code true}). + * + * @param value {@code true} to ping an idle channel + * @return this builder + */ + public Builder keepAliveWithoutCalls(boolean value) { + keepAliveWithoutCalls = value; + return this; + } + + /** + * Disables HTTP/2 keepalive entirely. + * + * @return this builder + */ + public Builder disableKeepAlive() { + keepAliveDisabled = true; + return this; + } + /** * Builds an immutable {@link MxGatewayClientOptions} from the current state. * diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java index b0fd0afa..39b6ea24 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/main/java/com/zb/mom/ww/mxgateway/client/MxGatewaySession.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; +import java.util.concurrent.atomic.AtomicLong; import mxaccess_gateway.v1.MxaccessGateway.ActivateCommand; import mxaccess_gateway.v1.MxaccessGateway.AddBufferedItemCommand; import mxaccess_gateway.v1.MxaccessGateway.AddItem2Command; @@ -74,7 +75,8 @@ import mxaccess_gateway.v1.MxaccessGateway.WriteSecuredBulkEntry; * command request carries a freshly generated client correlation id. */ public final class MxGatewaySession implements AutoCloseable { - private static final SecureRandom RANDOM = new SecureRandom(); + private static final String CORRELATION_PREFIX = newCorrelationPrefix(); + private static final AtomicLong CORRELATION_COUNTER = new AtomicLong(); private final MxGatewayClient client; private final OpenSessionReply openReply; @@ -151,7 +153,7 @@ public final class MxGatewaySession implements AutoCloseable { if (reply.hasRegister()) { return reply.getRegister().getServerHandle(); } - return reply.getReturnValue().getInt32Value(); + return int32ReturnValueOrThrow("Register", reply); } /** @@ -194,7 +196,7 @@ public final class MxGatewaySession implements AutoCloseable { if (reply.hasAddItem()) { return reply.getAddItem().getItemHandle(); } - return reply.getReturnValue().getInt32Value(); + return int32ReturnValueOrThrow("AddItem", reply); } /** @@ -228,7 +230,7 @@ public final class MxGatewaySession implements AutoCloseable { if (reply.hasAddItem2()) { return reply.getAddItem2().getItemHandle(); } - return reply.getReturnValue().getInt32Value(); + return int32ReturnValueOrThrow("AddItem2", reply); } /** @@ -351,6 +353,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllTagAddresses(tagAddresses)) .build()); + requirePayload("AddItemBulk", reply.hasAddItemBulk()); return reply.getAddItemBulk().getResultsList(); } @@ -371,6 +374,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllItemHandles(itemHandles)) .build()); + requirePayload("AdviseItemBulk", reply.hasAdviseItemBulk()); return reply.getAdviseItemBulk().getResultsList(); } @@ -391,6 +395,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllItemHandles(itemHandles)) .build()); + requirePayload("RemoveItemBulk", reply.hasRemoveItemBulk()); return reply.getRemoveItemBulk().getResultsList(); } @@ -411,6 +416,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllItemHandles(itemHandles)) .build()); + requirePayload("UnAdviseItemBulk", reply.hasUnAdviseItemBulk()); return reply.getUnAdviseItemBulk().getResultsList(); } @@ -432,6 +438,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllTagAddresses(tagAddresses)) .build()); + requirePayload("SubscribeBulk", reply.hasSubscribeBulk()); return reply.getSubscribeBulk().getResultsList(); } @@ -453,6 +460,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllItemHandles(itemHandles)) .build()); + requirePayload("UnsubscribeBulk", reply.hasUnsubscribeBulk()); return reply.getUnsubscribeBulk().getResultsList(); } @@ -478,6 +486,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllEntries(entries)) .build()); + requirePayload("WriteBulk", reply.hasWriteBulk()); return reply.getWriteBulk().getResultsList(); } @@ -500,6 +509,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllEntries(entries)) .build()); + requirePayload("Write2Bulk", reply.hasWrite2Bulk()); return reply.getWrite2Bulk().getResultsList(); } @@ -523,6 +533,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllEntries(entries)) .build()); + requirePayload("WriteSecuredBulk", reply.hasWriteSecuredBulk()); return reply.getWriteSecuredBulk().getResultsList(); } @@ -545,6 +556,7 @@ public final class MxGatewaySession implements AutoCloseable { .setServerHandle(serverHandle) .addAllEntries(entries)) .build()); + requirePayload("WriteSecured2Bulk", reply.hasWriteSecured2Bulk()); return reply.getWriteSecured2Bulk().getResultsList(); } @@ -593,6 +605,7 @@ public final class MxGatewaySession implements AutoCloseable { .addAllTagAddresses(tagAddresses) .setTimeoutMs(timeoutMs)) .build()); + requirePayload("ReadBulk", reply.hasReadBulk()); return reply.getReadBulk().getResultsList(); } @@ -1097,12 +1110,38 @@ public final class MxGatewaySession implements AutoCloseable { * @throws MxGatewayException on transport or protocol failure */ public List drainEvents(int maxEvents) { - return invokeCommand(MxCommand.newBuilder() - .setKind(MxCommandKind.MX_COMMAND_KIND_DRAIN_EVENTS) - .setDrainEvents(DrainEventsCommand.newBuilder().setMaxEvents(maxEvents)) - .build()) - .getDrainEvents() - .getEventsList(); + MxCommandReply reply = invokeCommand(MxCommand.newBuilder() + .setKind(MxCommandKind.MX_COMMAND_KIND_DRAIN_EVENTS) + .setDrainEvents(DrainEventsCommand.newBuilder().setMaxEvents(maxEvents)) + .build()); + requirePayload("DrainEvents", reply.hasDrainEvents()); + return reply.getDrainEvents().getEventsList(); + } + + /** + * Returns the int32 {@code return_value} of an OK reply that carried no typed + * payload, or throws. Returning a default {@code 0} would hand the caller a + * bogus handle that fails later with an unrelated invalid-handle error. + */ + private static int int32ReturnValueOrThrow(String operation, MxCommandReply reply) { + if (reply.hasReturnValue() && reply.getReturnValue().getKindCase() == MxValue.KindCase.INT32_VALUE) { + return reply.getReturnValue().getInt32Value(); + } + throw new MxGatewayMalformedReplyException( + operation + " returned a malformed reply: OK reply carried neither " + + "the typed payload nor an int32 return_value"); + } + + /** + * Throws when an OK reply lacks the typed payload a bulk or drain command + * must carry; an empty list read as "nothing subscribed, no failures" would + * be a silent wrong answer. + */ + private static void requirePayload(String operation, boolean present) { + if (!present) { + throw new MxGatewayMalformedReplyException( + operation + " returned a malformed reply: OK reply did not carry the " + operation + " payload"); + } } /** @@ -1277,9 +1316,18 @@ public final class MxGatewaySession implements AutoCloseable { return null; } - private static String newCorrelationId() { - byte[] bytes = new byte[16]; - RANDOM.nextBytes(bytes); + /** + * Correlation ids are diagnostic, not security tokens: a per-process random + * prefix plus a lock-free counter is unique without the shared + * {@code SecureRandom} contention a per-call draw causes under concurrency. + */ + private static String newCorrelationPrefix() { + byte[] bytes = new byte[8]; + new SecureRandom().nextBytes(bytes); return HexFormat.of().formatHex(bytes); } + + static String newCorrelationId() { + return CORRELATION_PREFIX + String.format("%016x", CORRELATION_COUNTER.incrementAndGet()); + } } diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxEventStreamTests.java b/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxEventStreamTests.java index b2ef3754..7a6950aa 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxEventStreamTests.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxEventStreamTests.java @@ -41,7 +41,7 @@ final class MxEventStreamTests { Thread.currentThread().interrupt(); try { - assertThrows(io.grpc.StatusRuntimeException.class, stream::hasNext); + assertThrows(MxGatewayException.class, stream::hasNext); assertTrue(Thread.currentThread().isInterrupted(), "interrupt flag restored"); assertEquals(1, call.cancelCount.get(), "call cancelled on interrupt"); } finally { diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientHardeningTests.java b/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientHardeningTests.java new file mode 100644 index 00000000..39ad3629 --- /dev/null +++ b/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientHardeningTests.java @@ -0,0 +1,283 @@ +package com.zb.mom.ww.mxgateway.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import galaxy_repository.v1.GalaxyRepositoryOuterClass.DeployEvent; +import galaxy_repository.v1.GalaxyRepositoryOuterClass.WatchDeployEventsRequest; +import io.grpc.Status; +import io.grpc.stub.ClientCallStreamObserver; +import io.grpc.stub.ServerCallStreamObserver; +import io.grpc.stub.StreamObserver; +import io.grpc.Server; +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import java.net.InetSocketAddress; +import java.time.Duration; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import mxaccess_gateway.v1.MxAccessGatewayGrpc; +import mxaccess_gateway.v1.MxaccessGateway.DrainEventsReply; +import mxaccess_gateway.v1.MxaccessGateway.MxCommandReply; +import mxaccess_gateway.v1.MxaccessGateway.MxCommandRequest; +import mxaccess_gateway.v1.MxaccessGateway.MxEvent; +import mxaccess_gateway.v1.MxaccessGateway.ProtocolStatus; +import mxaccess_gateway.v1.MxaccessGateway.ProtocolStatusCode; +import mxaccess_gateway.v1.MxaccessGateway.StreamEventsRequest; +import org.junit.jupiter.api.Test; + +/** Regression tests for the 2026-12 client review (CJV-001/003/004/005/006/007). */ +final class MxGatewayClientHardeningTests { + @Test + void keepAliveDefaultsMatchTheGatewayPolicyAndAreConfigurable() { + MxGatewayClientOptions defaults = + MxGatewayClientOptions.builder().endpoint("localhost:1").build(); + assertEquals(Duration.ofSeconds(30), defaults.keepAliveTime()); + assertEquals(Duration.ofSeconds(10), defaults.keepAliveTimeout()); + assertTrue(defaults.keepAliveWithoutCalls()); + + MxGatewayClientOptions tuned = MxGatewayClientOptions.builder() + .endpoint("localhost:1") + .keepAliveTime(Duration.ofSeconds(45)) + .keepAliveTimeout(Duration.ofSeconds(5)) + .keepAliveWithoutCalls(false) + .build(); + assertEquals(Duration.ofSeconds(45), tuned.keepAliveTime()); + assertEquals(Duration.ofSeconds(5), tuned.keepAliveTimeout()); + assertFalse(tuned.keepAliveWithoutCalls()); + + assertNull(MxGatewayClientOptions.builder() + .endpoint("localhost:1") + .disableKeepAlive() + .build() + .keepAliveTime()); + } + + @Test + void eventStreamMapsStatusErrorsToTypedExceptions() { + MxEventStream stream = new MxEventStream(4); + stream.observer().onError(Status.PERMISSION_DENIED + .withDescription("key mxgw_id_secret is not the owner") + .asRuntimeException()); + + MxGatewayAuthorizationException error = + assertThrows(MxGatewayAuthorizationException.class, stream::hasNext); + assertFalse(error.getMessage().contains("secret"), error.getMessage()); + } + + @Test + void eventStreamMapsUnavailableToGatewayException() { + MxEventStream stream = new MxEventStream(4); + stream.observer().onError(Status.UNAVAILABLE.asRuntimeException()); + + assertThrows(MxGatewayException.class, stream::hasNext); + } + + @Test + void deployEventStreamMapsStatusErrorsToTypedExceptions() { + DeployEventStream stream = new DeployEventStream(4); + stream.observer().onError(Status.UNAUTHENTICATED.asRuntimeException()); + + assertThrows(MxGatewayAuthenticationException.class, stream::hasNext); + } + + @Test + void deployEventStreamInterruptCancelsCallAndRestoresInterruptFlag() { + DeployEventStream stream = new DeployEventStream(4); + CountingCall call = new CountingCall(); + stream.observer().beforeStart(call); + + Thread.currentThread().interrupt(); + try { + assertThrows(MxGatewayException.class, stream::hasNext); + assertTrue(Thread.currentThread().isInterrupted(), "interrupt flag restored"); + assertEquals(1, call.cancelCount.get(), "call cancelled on interrupt"); + } finally { + Thread.interrupted(); + } + } + + @Test + void helpersRejectAnOkReplyWithoutThePayload() throws Exception { + MxAccessGatewayGrpc.MxAccessGatewayImplBase service = new MxAccessGatewayGrpc.MxAccessGatewayImplBase() { + @Override + public void invoke(MxCommandRequest request, StreamObserver responseObserver) { + responseObserver.onNext(MxCommandReply.newBuilder() + .setSessionId(request.getSessionId()) + .setKind(request.getCommand().getKind()) + .setProtocolStatus(ProtocolStatus.newBuilder() + .setCode(ProtocolStatusCode.PROTOCOL_STATUS_CODE_OK)) + .build()); + responseObserver.onCompleted(); + } + }; + String name = "mxgw-java-malformed-" + UUID.randomUUID(); + Server server = InProcessServerBuilder.forName(name) + .directExecutor() + .addService(service) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(name).directExecutor().build(); + try { + MxGatewayClient client = new MxGatewayClient( + channel, + MxGatewayClientOptions.builder() + .endpoint("in-process") + .plaintext(true) + .build()); + MxGatewaySession session = MxGatewaySession.forSessionId(client, "s1"); + + assertThrows(MxGatewayMalformedReplyException.class, () -> session.register("c")); + assertThrows(MxGatewayMalformedReplyException.class, () -> session.addItem(1, "t")); + assertThrows(MxGatewayMalformedReplyException.class, () -> session.addItem2(1, "t", "c")); + assertThrows( + MxGatewayMalformedReplyException.class, + () -> session.subscribeBulk(1, java.util.List.of("t"))); + assertThrows( + MxGatewayMalformedReplyException.class, + () -> session.readBulk(1, java.util.List.of("t"), Duration.ZERO)); + assertThrows(MxGatewayMalformedReplyException.class, () -> session.drainEvents(10)); + } finally { + channel.shutdownNow(); + server.shutdownNow(); + } + } + + @Test + void emptyBulkPayloadIsStillAValidEmptyResult() throws Exception { + MxAccessGatewayGrpc.MxAccessGatewayImplBase service = new MxAccessGatewayGrpc.MxAccessGatewayImplBase() { + @Override + public void invoke(MxCommandRequest request, StreamObserver responseObserver) { + responseObserver.onNext(MxCommandReply.newBuilder() + .setProtocolStatus(ProtocolStatus.newBuilder() + .setCode(ProtocolStatusCode.PROTOCOL_STATUS_CODE_OK)) + .setDrainEvents(DrainEventsReply.getDefaultInstance()) + .build()); + responseObserver.onCompleted(); + } + }; + String name = "mxgw-java-empty-" + UUID.randomUUID(); + Server server = InProcessServerBuilder.forName(name) + .directExecutor() + .addService(service) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(name).directExecutor().build(); + try { + MxGatewayClient client = new MxGatewayClient( + channel, + MxGatewayClientOptions.builder() + .endpoint("in-process") + .plaintext(true) + .build()); + assertTrue(MxGatewaySession.forSessionId(client, "s1").drainEvents(10).isEmpty()); + } finally { + channel.shutdownNow(); + server.shutdownNow(); + } + } + + @Test + void correlationIdsAreUniqueAndFixedWidth() { + String first = MxGatewaySession.newCorrelationId(); + String second = MxGatewaySession.newCorrelationId(); + assertNotEquals(first, second); + assertEquals(32, first.length()); + assertEquals(32, second.length()); + } + + @Test + void closeCancelsOpenStreamsAndWakesBlockedReaders() throws Exception { + CountDownLatch streamStarted = new CountDownLatch(1); + MxAccessGatewayGrpc.MxAccessGatewayImplBase service = new MxAccessGatewayGrpc.MxAccessGatewayImplBase() { + @Override + public void streamEvents(StreamEventsRequest request, StreamObserver responseObserver) { + // Never completes: a deadline-less stream on a quiet tag. + ((ServerCallStreamObserver) responseObserver).setOnCancelHandler(() -> { }); + streamStarted.countDown(); + } + }; + Server server = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .addService(service) + .build() + .start(); + MxGatewayClient client = MxGatewayClient.connect(MxGatewayClientOptions.builder() + .endpoint("127.0.0.1:" + server.getPort()) + .plaintext(true) + .build()); + try { + MxEventStream stream = client.streamEvents(StreamEventsRequest.getDefaultInstance()); + AtomicReference outcome = new AtomicReference<>(); + CountDownLatch readerDone = new CountDownLatch(1); + Thread reader = new Thread(() -> { + try { + stream.hasNext(); + } catch (Throwable error) { + outcome.set(error); + } finally { + readerDone.countDown(); + } + }); + reader.start(); + assertTrue(streamStarted.await(5, TimeUnit.SECONDS), "stream reached the server"); + + client.close(); + + assertTrue(readerDone.await(5, TimeUnit.SECONDS), "blocked reader was woken by close()"); + } finally { + client.close(); + server.shutdownNow(); + } + } + + private static final class CountingCall extends ClientCallStreamObserver { + final AtomicInteger cancelCount = new AtomicInteger(); + + @Override + public void cancel(String message, Throwable cause) { + cancelCount.incrementAndGet(); + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setOnReadyHandler(Runnable onReadyHandler) { + } + + @Override + public void request(int count) { + } + + @Override + public void setMessageCompression(boolean enable) { + } + + @Override + public void disableAutoInboundFlowControl() { + } + + @Override + public void onNext(WatchDeployEventsRequest value) { + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onCompleted() { + } + } +} diff --git a/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientTlsTests.java b/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientTlsTests.java index 42fe0b7f..e77e0617 100644 --- a/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientTlsTests.java +++ b/clients/java/zb-mom-ww-mxgateway-client/src/test/java/com/zb/mom/ww/mxgateway/client/MxGatewayClientTlsTests.java @@ -109,6 +109,7 @@ final class MxGatewayClientTlsTests { .forAddress(new InetSocketAddress("127.0.0.1", 0)) .sslContext(GrpcSslContexts.forServer(certPemFile, keyPemFile).build()) .addService(new MinimalGatewayService()) + .addService(new MinimalGalaxyService()) .build() .start(); port = server.getPort(); @@ -156,6 +157,22 @@ final class MxGatewayClientTlsTests { } } + @Test + void galaxyClientConnectsToSelfSignedServer_WhenRequireCertificateValidationIsFalse() { + // CJV-002: GalaxyRepositoryClient must honour the same lenient-TLS default + // as MxGatewayClient instead of validating against the JVM trust store. + MxGatewayClientOptions options = MxGatewayClientOptions.builder() + .endpoint("127.0.0.1:" + port) + .apiKey("test-key") + .connectTimeout(Duration.ofSeconds(5)) + .callTimeout(Duration.ofSeconds(5)) + .build(); + + try (GalaxyRepositoryClient client = GalaxyRepositoryClient.connect(options)) { + assertTrue(client.testConnection()); + } + } + @Test void failsToConnect_WhenRequireCertificateValidationIsTrue() throws SSLException { MxGatewayClientOptions options = MxGatewayClientOptions.builder() @@ -179,6 +196,22 @@ final class MxGatewayClientTlsTests { } } + /** Minimal Galaxy Repository stub that succeeds TestConnection. */ + private static final class MinimalGalaxyService + extends galaxy_repository.v1.GalaxyRepositoryGrpc.GalaxyRepositoryImplBase { + @Override + public void testConnection( + galaxy_repository.v1.GalaxyRepositoryOuterClass.TestConnectionRequest request, + StreamObserver + responseObserver) { + responseObserver.onNext(galaxy_repository.v1.GalaxyRepositoryOuterClass.TestConnectionReply + .newBuilder() + .setOk(true) + .build()); + responseObserver.onCompleted(); + } + } + /** Minimal gateway stub that succeeds any OpenSession call. */ private static final class MinimalGatewayService extends MxAccessGatewayGrpc.MxAccessGatewayImplBase {