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 { diff --git a/clients/python/README.md b/clients/python/README.md index f5790ea2..20b12951 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -455,6 +455,32 @@ building it inside `asyncio.to_thread` raises `RuntimeError: There is no current event loop in thread 'asyncio_N'`. Callers that build their own channel should keep `create_channel` on the loop thread. +## Keepalive And Error Mapping + +The channel sends an HTTP/2 PING every 30 s, waits 10 s for the acknowledgement, +and pings even while no call is active (`grpc.keepalive_time_ms`, +`grpc.keepalive_timeout_ms`, `grpc.keepalive_permit_without_calls`, and +`grpc.http2.max_pings_without_data=0` so pings continue with no data in flight). +A half-open connection (firewall idle-out, host power loss) therefore makes a +deadline-less `stream_events()` iterator raise `MxGatewayTransportError` within +about 40 s instead of hanging forever. Tune with `ClientOptions(keepalive_time=..., +keepalive_timeout=..., keepalive_permit_without_calls=...)`; `keepalive_time=None` +disables it. Keep `keepalive_time` 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`). + +gRPC failures map to `MxGatewayAuthenticationError`, `MxGatewayAuthorizationError`, +`MxGatewayTimeoutError` (`DEADLINE_EXCEEDED`), `MxGatewayUnavailableError` +(`UNAVAILABLE` / `RESOURCE_EXHAUSTED`) or the base `MxGatewayTransportError`. Every +transport error carries the gRPC status in `.code`, and credential-shaped text +(`mxgw_...` keys, `Bearer`) is scrubbed from the server-supplied details. Enum +values newer than the generated code (a new status category or protocol status +code) are reported by number instead of raising `ValueError`. + +`register`, `add_item`, `add_item2`, the bulk helpers, `read_bulk` and +`drain_events` raise `MalformedReplyError` when an `OK` reply lacks the expected +payload, instead of returning handle `0` or an empty list. + ## CLI The CLI emits deterministic JSON for automation: @@ -472,8 +498,15 @@ mxgw-py write --session-id --server-handle 1 --item-handle 2 --type int32 - ``` Use `--api-key` or `--api-key-env MXGATEWAY_API_KEY` to attach API key -metadata. `smoke` opens a session, registers, adds an item, advises, streams a -bounded event count, and closes the session in a `finally` block. +metadata. `smoke` opens a session, registers, adds an item, attaches the event +stream, advises, collects a bounded event count, and closes the session in a +`finally` block. It attaches the stream before advising (and, when the gateway +lists `stream-events-attached-ack`, waits for the attach acknowledgement) so the +initial value cannot be published before the subscriber registers. + +`batch` reads one command per stdin line and runs them all on a single event loop, +reusing one client (one channel, one TLS certificate probe) per distinct +connection until stdin ends; it closes them once at the end. Use TLS options for a secured gateway: diff --git a/clients/python/src/zb_mom_ww_mxgateway/__init__.py b/clients/python/src/zb_mom_ww_mxgateway/__init__.py index 1f8f31ba..2cf0e0c9 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/__init__.py +++ b/clients/python/src/zb_mom_ww_mxgateway/__init__.py @@ -18,7 +18,9 @@ from .errors import ( MxGatewayCommandError, MxGatewayError, MxGatewaySessionError, + MxGatewayTimeoutError, MxGatewayTransportError, + MxGatewayUnavailableError, MxGatewayWorkerError, ) from .options import BrowseChildrenOptions, ClientOptions @@ -43,7 +45,9 @@ __all__ = [ "MxGatewayCommandError", "MxGatewayError", "MxGatewaySessionError", + "MxGatewayTimeoutError", "MxGatewayTransportError", + "MxGatewayUnavailableError", "MxGatewayWorkerError", "MxValueView", "ReplayGap", diff --git a/clients/python/src/zb_mom_ww_mxgateway/auth.py b/clients/python/src/zb_mom_ww_mxgateway/auth.py index 8d21f08b..831528f9 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/auth.py +++ b/clients/python/src/zb_mom_ww_mxgateway/auth.py @@ -1,5 +1,6 @@ """Authentication metadata helpers for MXAccess Gateway clients.""" +import re from collections.abc import Sequence from dataclasses import dataclass @@ -51,6 +52,21 @@ def merge_metadata( return tuple(merged) +_CREDENTIAL_PATTERN = re.compile(r"mxgw_[A-Za-z0-9_-]+|\bbearer\b", re.IGNORECASE) + + +def redact_credentials(text: str | None) -> str: + """Scrub credential-shaped text (``mxgw__`` keys, ``Bearer``) from `text`. + + Library users get this on every mapped gRPC error without having to supply + the secret; a proxy or gateway error path can echo the authorization value. + """ + + if not text: + return text or "" + return _CREDENTIAL_PATTERN.sub(REDACTED, text) + + def redact_secret(text: str, secrets: Sequence[str | None]) -> str: """Replace known secret values with a stable redaction marker.""" diff --git a/clients/python/src/zb_mom_ww_mxgateway/errors.py b/clients/python/src/zb_mom_ww_mxgateway/errors.py index ca2770c0..4f06c704 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/errors.py +++ b/clients/python/src/zb_mom_ww_mxgateway/errors.py @@ -6,9 +6,23 @@ from typing import Any import grpc +from .auth import redact_credentials from .generated import mxaccess_gateway_pb2 as pb +def _enum_name(enum_type: Any, value: int) -> str: + """Return the enum member name, or the number when the value is unknown. + + proto3 enums are open: a gateway newer than this client's generated code can + send a value the client has no name for, and ``Name()`` would raise + ``ValueError`` in place of the typed gateway error being built. + """ + try: + return str(enum_type.Name(value)) + except ValueError: + return str(value) + + class MxGatewayError(Exception): """Base class for client wrapper errors.""" @@ -26,7 +40,24 @@ class MxGatewayError(Exception): class MxGatewayTransportError(MxGatewayError): - """Transport-level gRPC failure.""" + """Transport-level gRPC failure. + + `code` is the gRPC status code that produced it (``None`` when the error did + not come from a status), so reconnect/backoff logic does not have to reach + into ``__cause__``. + """ + + def __init__( + self, + message: str, + *, + protocol_status: pb.ProtocolStatus | None = None, + raw_reply: Any | None = None, + code: grpc.StatusCode | None = None, + ) -> None: + """Initialize with a message and the optional gRPC status code.""" + super().__init__(message, protocol_status=protocol_status, raw_reply=raw_reply) + self.code = code class MxGatewayAuthenticationError(MxGatewayTransportError): @@ -37,6 +68,14 @@ class MxGatewayAuthorizationError(MxGatewayTransportError): """Authorization failure reported by gRPC.""" +class MxGatewayTimeoutError(MxGatewayTransportError): + """The call's deadline expired (``DEADLINE_EXCEEDED``); a write may or may not have applied.""" + + +class MxGatewayUnavailableError(MxGatewayTransportError): + """The gateway is unreachable or shedding load (``UNAVAILABLE`` / ``RESOURCE_EXHAUSTED``).""" + + class MxGatewaySessionError(MxGatewayError): """Gateway session failure.""" @@ -58,18 +97,27 @@ class MalformedReplyError(MxGatewayError): def map_rpc_error(operation: str, error: grpc.RpcError) -> MxGatewayTransportError: - """Map a generated gRPC exception to the client exception hierarchy.""" + """Map a generated gRPC exception to the client exception hierarchy. + + The status code is preserved on the result (``.code``), distinct types cover + the cases a retry loop must tell apart, and credential-shaped text is scrubbed + from the server-supplied details. + """ code = error.code() if hasattr(error, "code") else None details = error.details() if hasattr(error, "details") else str(error) - message = f"{operation} failed: {details}" + message = f"{operation} failed: {redact_credentials(details)}" if code == grpc.StatusCode.UNAUTHENTICATED: - return MxGatewayAuthenticationError(message) + return MxGatewayAuthenticationError(message, code=code) if code == grpc.StatusCode.PERMISSION_DENIED: - return MxGatewayAuthorizationError(message) + return MxGatewayAuthorizationError(message, code=code) + if code == grpc.StatusCode.DEADLINE_EXCEEDED: + return MxGatewayTimeoutError(message, code=code) + if code in (grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.RESOURCE_EXHAUSTED): + return MxGatewayUnavailableError(message, code=code) - return MxGatewayTransportError(message) + return MxGatewayTransportError(message, code=code) def ensure_protocol_success( @@ -92,7 +140,7 @@ def ensure_protocol_success( return raw_reply message_text = protocol_status.message if protocol_status else "" - message = f"{operation} failed: {message_text or pb.ProtocolStatusCode.Name(code)}" + message = f"{operation} failed: {message_text or _enum_name(pb.ProtocolStatusCode, code)}" if code in ( pb.PROTOCOL_STATUS_CODE_SESSION_NOT_FOUND, @@ -166,7 +214,7 @@ def _mxaccess_message(operation: str, reply: pb.MxCommandReply) -> str: # verbatim for diagnostic parity with the other clients. `category` remains # the authoritative verdict; `success` is diagnostics only. for status in reply.statuses: - category = pb.MxStatusCategory.Name(status.category) + category = _enum_name(pb.MxStatusCategory, status.category) message += ( f" [success={status.success}, category={category}, " f"detail={status.detail}, {status.diagnostic_text}]" diff --git a/clients/python/src/zb_mom_ww_mxgateway/options.py b/clients/python/src/zb_mom_ww_mxgateway/options.py index ea3e38bf..867b9eac 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/options.py +++ b/clients/python/src/zb_mom_ww_mxgateway/options.py @@ -30,6 +30,16 @@ class ClientOptions: call_timeout: float | None = 30.0 stream_timeout: float | None = None max_grpc_message_bytes: int = 16 * 1024 * 1024 + #: HTTP/2 keepalive ping interval in seconds (``None`` disables keepalive). + #: Keep it at or above the gateway's permitted client ping interval (30 s by + #: default) or the gateway answers with GOAWAY (``too_many_pings``). + keepalive_time: float | None = 30.0 + #: Seconds to wait for a keepalive ping acknowledgement before the + #: connection is treated as dead. + keepalive_timeout: float = 10.0 + #: Send keepalive pings while no call is active. Required so an idle channel + #: between calls is still probed. + keepalive_permit_without_calls: bool = True def __post_init__(self) -> None: """Validate options; raise `ValueError` for invalid combinations.""" @@ -44,6 +54,10 @@ class ClientOptions: raise ValueError("stream_timeout must be greater than zero") if self.max_grpc_message_bytes <= 0: raise ValueError("max_grpc_message_bytes must be greater than zero") + if self.keepalive_time is not None and self.keepalive_time <= 0: + raise ValueError("keepalive_time must be greater than zero") + if self.keepalive_timeout <= 0: + raise ValueError("keepalive_timeout must be greater than zero") def __repr__(self) -> str: """Return a repr that redacts the API key value.""" @@ -56,7 +70,10 @@ class ClientOptions: f"server_name_override={self.server_name_override!r}, " f"call_timeout={self.call_timeout!r}, " f"stream_timeout={self.stream_timeout!r}, " - f"max_grpc_message_bytes={self.max_grpc_message_bytes!r})" + f"max_grpc_message_bytes={self.max_grpc_message_bytes!r}, " + f"keepalive_time={self.keepalive_time!r}, " + f"keepalive_timeout={self.keepalive_timeout!r}, " + f"keepalive_permit_without_calls={self.keepalive_permit_without_calls!r})" ) @@ -191,6 +208,22 @@ def create_channel( ("grpc.max_receive_message_length", options.max_grpc_message_bytes), ("grpc.max_send_message_length", options.max_grpc_message_bytes), ] + if options.keepalive_time is not None: + # Without keepalive a half-open connection (firewall idle-out, host power + # loss) leaves a deadline-less stream waiting forever. + # `max_pings_without_data=0` lets the client keep pinging with no data in + # flight; the gateway's matching ping policy permits the 30 s interval. + channel_options.extend( + [ + ("grpc.keepalive_time_ms", int(options.keepalive_time * 1000)), + ("grpc.keepalive_timeout_ms", int(options.keepalive_timeout * 1000)), + ( + "grpc.keepalive_permit_without_calls", + 1 if options.keepalive_permit_without_calls else 0, + ), + ("grpc.http2.max_pings_without_data", 0), + ] + ) if options.server_name_override: channel_options.append(("grpc.ssl_target_name_override", options.server_name_override)) elif security.target_name_override: diff --git a/clients/python/src/zb_mom_ww_mxgateway/session.py b/clients/python/src/zb_mom_ww_mxgateway/session.py index 90c8b066..e0d2dbe1 100644 --- a/clients/python/src/zb_mom_ww_mxgateway/session.py +++ b/clients/python/src/zb_mom_ww_mxgateway/session.py @@ -94,7 +94,9 @@ class Session: ), correlation_id=correlation_id, ) - return reply.register.server_handle + if reply.HasField("register"): + return reply.register.server_handle + return _int32_return_value_or_raise("register", reply) async def unregister(self, server_handle: int, *, correlation_id: str = "") -> None: """Invoke MXAccess `Unregister` for a previously registered `ServerHandle`.""" @@ -143,7 +145,9 @@ class Session: ), correlation_id=correlation_id, ) - return reply.add_item.item_handle + if reply.HasField("add_item"): + return reply.add_item.item_handle + return _int32_return_value_or_raise("add_item", reply) async def add_item2( self, @@ -165,7 +169,9 @@ class Session: ), correlation_id=correlation_id, ) - return reply.add_item2.item_handle + if reply.HasField("add_item2"): + return reply.add_item2.item_handle + return _int32_return_value_or_raise("add_item2", reply) async def advise( self, @@ -226,6 +232,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("add_item_bulk", reply) return list(reply.add_item_bulk.results) async def advise_item_bulk( @@ -249,6 +256,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("advise_item_bulk", reply) return list(reply.advise_item_bulk.results) async def remove_item_bulk( @@ -272,6 +280,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("remove_item_bulk", reply) return list(reply.remove_item_bulk.results) async def unadvise_item_bulk( @@ -295,6 +304,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("un_advise_item_bulk", reply) return list(reply.un_advise_item_bulk.results) async def subscribe_bulk( @@ -318,6 +328,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("subscribe_bulk", reply) return list(reply.subscribe_bulk.results) async def unsubscribe_bulk( @@ -341,6 +352,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("unsubscribe_bulk", reply) return list(reply.unsubscribe_bulk.results) async def write_bulk( @@ -369,6 +381,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("write_bulk", reply) return list(reply.write_bulk.results) async def write2_bulk( @@ -392,6 +405,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("write2_bulk", reply) return list(reply.write2_bulk.results) async def write_secured_bulk( @@ -415,6 +429,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("write_secured_bulk", reply) return list(reply.write_secured_bulk.results) async def write_secured2_bulk( @@ -438,6 +453,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("write_secured2_bulk", reply) return list(reply.write_secured2_bulk.results) async def read_bulk( @@ -477,6 +493,7 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("read_bulk", reply) return list(reply.read_bulk.results) async def write( @@ -895,15 +912,24 @@ class Session: ), correlation_id=correlation_id, ) + _require_payload("drain_events", reply) return list(reply.drain_events.events) def stream_events( self, *, after_worker_sequence: int = 0, + emit_stream_attached: bool = False, ) -> AsyncIterator[pb.MxEvent | ReplayGap]: """Return an async iterator over this session's `MxEvent` stream. + With *emit_stream_attached* the gateway sends one ``stream_attached`` + sentinel event first, after this stream's subscriber is registered; wait + for it before ``advise`` / ``subscribe_bulk`` so the initial value cannot + be lost to the attach race. Only request it when the session's + ``open_reply.capabilities`` lists ``stream-events-attached-ack``; the + sentinel is yielded as an ``MxEvent`` with ``HasField("stream_attached")``. + Each yielded item is either a normal :class:`~...MxEvent` or a :class:`ReplayGap`. Branch on ``isinstance(item, ReplayGap)`` — a gap is never delivered as an ``MxEvent`` so it cannot be mistaken for a real @@ -923,6 +949,7 @@ class Session: pb.StreamEventsRequest( session_id=self.session_id, after_worker_sequence=after_worker_sequence, + emit_stream_attached=emit_stream_attached, ), ) return _surface_replay_gaps(raw) @@ -978,6 +1005,34 @@ def _value_secrets(value: MxValueInput) -> list[str]: return [] +def _int32_return_value_or_raise(operation: str, reply: Any) -> int: + """Return the int32 ``return_value`` of an OK reply lacking the typed payload, or raise. + + Returning the protobuf default ``0`` would hand the caller a bogus handle that + fails later with an unrelated invalid-handle error. + """ + if reply.HasField("return_value") and reply.return_value.WhichOneof("kind") == "int32_value": + return int(reply.return_value.int32_value) + raise MalformedReplyError( + f"{operation} returned a malformed reply: OK reply carried " + "neither the typed payload nor an int32 return_value", + raw_reply=reply, + ) + + +def _require_payload(field: str, reply: Any) -> None: + """Raise `MalformedReplyError` when an OK reply lacks the typed payload ``field``. + + An empty list read as "nothing subscribed, no failures" would be a silent + wrong answer for the bulk and drain commands. + """ + if not reply.HasField(field): + raise MalformedReplyError( + f"{field} returned a malformed reply: OK reply did not carry the {field} payload", + raw_reply=reply, + ) + + def _redact_error(error: MxGatewayError, secrets: Sequence[str | None]) -> None: """Scrub secret substrings from a raised error's message and reply in place. diff --git a/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py b/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py index fa05282e..2900beca 100644 --- a/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py +++ b/clients/python/src/zb_mom_ww_mxgateway_cli/commands.py @@ -40,6 +40,71 @@ DEFAULT_OPERATOR_PASSWORD_ENV = "MXGATEWAY_OPERATOR_PASSWORD" _BATCH_EOR = "__MXGW_BATCH_EOR__" +#: `OpenSessionReply.capabilities` entry advertising `StreamEventsRequest.emit_stream_attached`. +_STREAM_ATTACHED_CAPABILITY = "stream-events-attached-ack" + + +class _BatchContext: + """Process-wide state that lets batch mode reuse one loop and one client per connection. + + Batch mode exists to avoid per-command start-up cost. Re-entering Click per line + used to run ``asyncio.run`` (a new loop), dial a new channel and, on the lenient + TLS path, run a separate blocking TOFU certificate probe every time. While a + batch is active ``_run`` drives every command on ``loop`` and ``_connect`` / + ``_connect_galaxy`` hand out a cached client per distinct connection whose + ``async with`` exit does not close it; the batch closes them all once at the end. + """ + + def __init__(self) -> None: + self.loop = asyncio.new_event_loop() + self.gateway_clients: dict[tuple[Any, ...], GatewayClient] = {} + self.galaxy_clients: dict[tuple[Any, ...], GalaxyRepositoryClient] = {} + + def close(self) -> None: + async def _close_all() -> None: + for client in [*self.gateway_clients.values(), *self.galaxy_clients.values()]: + with contextlib.suppress(Exception): + await client.close() + + try: + self.loop.run_until_complete(_close_all()) + finally: + self.loop.close() + + +_batch_context: _BatchContext | None = None + + +class _SharedClient: + """Wrap a batch-cached client so ``async with`` yields it without closing it.""" + + def __init__(self, client: Any) -> None: + self._client = client + + async def __aenter__(self) -> Any: + return self._client + + async def __aexit__(self, *_exc_info: object) -> None: + return None + + def __getattr__(self, name: str) -> Any: + return getattr(self._client, name) + + +def _connection_key(kwargs: dict[str, Any]) -> tuple[Any, ...]: + """Identity of a connection: every option that changes how the channel is dialed.""" + + return ( + kwargs["endpoint"], + kwargs.get("api_key") or _api_key_from_env(kwargs.get("api_key_env")), + _use_plaintext(kwargs), + kwargs.get("ca_file"), + bool(kwargs.get("require_certificate_validation")), + kwargs.get("server_name_override"), + kwargs.get("call_timeout"), + kwargs.get("stream_timeout"), + ) + @click.group() def main() -> None: @@ -75,6 +140,16 @@ def batch() -> None: dispatcher would silently spawn a nested loop reading from the same exhausted stdin. """ + global _batch_context + _batch_context = _BatchContext() + try: + _run_batch_loop() + finally: + context, _batch_context = _batch_context, None + context.close() + + +def _run_batch_loop() -> None: for raw_line in sys.stdin: line = raw_line.rstrip("\n").rstrip("\r") if not line: @@ -1234,12 +1309,29 @@ async def _smoke(**kwargs: Any) -> dict[str, Any]: async with session: server_handle = await session.register(kwargs["client_name"]) item_handle = await session.add_item(server_handle, kwargs["item"]) - await session.advise(server_handle, item_handle) - events = await _collect_events( - session.stream_events(), - max_events=kwargs["max_events"], - timeout=kwargs["timeout"], - ) + # Attach the event stream BEFORE advising: a fresh stream does not + # replay the ring, so an initial OnDataChange published before the + # subscriber registers would be lost (CPY-006). When the gateway + # advertises the attach acknowledgement, wait for the sentinel so the + # subscriber is known to be registered before the advise is issued. + capabilities = session.open_reply.capabilities if session.open_reply else () + attach_ack = _STREAM_ATTACHED_CAPABILITY in capabilities + iterator = session.stream_events(emit_stream_attached=attach_ack).__aiter__() + try: + leading: list[pb.MxEvent | ReplayGap] = [] + if attach_ack: + leading = await _await_stream_attached(iterator, timeout=kwargs["timeout"]) + await session.advise(server_handle, item_handle) + events = await _collect_events( + iterator, + max_events=kwargs["max_events"], + timeout=kwargs["timeout"], + leading=leading, + ) + finally: + close = getattr(iterator, "aclose", None) + if close is not None: + await close() return { "sessionId": session.session_id, "serverHandle": server_handle, @@ -1458,6 +1550,18 @@ async def _galaxy_watch(**kwargs: Any) -> dict[str, Any]: async def _connect(kwargs: dict[str, Any]) -> GatewayClient: + context = _batch_context + if context is None: + return await _connect_new(kwargs) + key = _connection_key(kwargs) + client = context.gateway_clients.get(key) + if client is None: + client = await _connect_new(kwargs) + context.gateway_clients[key] = client + return _SharedClient(client) # type: ignore[return-value] + + +async def _connect_new(kwargs: dict[str, Any]) -> GatewayClient: api_key = kwargs.get("api_key") or _api_key_from_env(kwargs.get("api_key_env")) return await GatewayClient.connect( ClientOptions( @@ -1474,6 +1578,18 @@ async def _connect(kwargs: dict[str, Any]) -> GatewayClient: async def _connect_galaxy(kwargs: dict[str, Any]) -> GalaxyRepositoryClient: + context = _batch_context + if context is None: + return await _connect_galaxy_new(kwargs) + key = _connection_key(kwargs) + client = context.galaxy_clients.get(key) + if client is None: + client = await _connect_galaxy_new(kwargs) + context.galaxy_clients[key] = client + return _SharedClient(client) # type: ignore[return-value] + + +async def _connect_galaxy_new(kwargs: dict[str, Any]) -> GalaxyRepositoryClient: api_key = kwargs.get("api_key") or _api_key_from_env(kwargs.get("api_key_env")) return await GalaxyRepositoryClient.connect( ClientOptions( @@ -1526,6 +1642,15 @@ def _secrets(kwargs: dict[str, Any]) -> list[str | None]: ] +def _run_awaitable(awaitable: Awaitable[Any]) -> Any: + """Run `awaitable` on the batch loop when a batch is active, else on a fresh loop.""" + + context = _batch_context + if context is None: + return asyncio.run(awaitable) # type: ignore[arg-type] + return context.loop.run_until_complete(awaitable) + + def _run( awaitable: Awaitable[dict[str, Any]], *, @@ -1533,7 +1658,7 @@ def _run( secrets: list[str | None], ) -> None: try: - payload = asyncio.run(awaitable) + payload = _run_awaitable(awaitable) except MxGatewayError as error: raise click.ClickException(redact_secret(str(error), secrets)) from error @@ -1546,7 +1671,7 @@ def _run_streaming( secrets: list[str | None], ) -> None: try: - asyncio.run(awaitable) + _run_awaitable(awaitable) except MxGatewayError as error: raise click.ClickException(redact_secret(str(error), secrets)) from error @@ -1570,11 +1695,35 @@ def _emit( click.echo(text or rendered_text or json.dumps(payload, sort_keys=True)) +async def _await_stream_attached( + iterator: Any, + *, + timeout: float, +) -> list[pb.MxEvent | ReplayGap]: + """Wait for the ``stream_attached`` sentinel; return any real items read meanwhile. + + The sentinel is consumed, not returned: it is an attach acknowledgement, not an + MXAccess event. A timeout or an early end of stream is tolerated (the caller then + proceeds best-effort, as against a gateway that never sends the sentinel). + """ + + leading: list[pb.MxEvent | ReplayGap] = [] + try: + while True: + item = await asyncio.wait_for(iterator.__anext__(), timeout=timeout) + if not isinstance(item, ReplayGap) and item.HasField("stream_attached"): + return leading + leading.append(item) + except (StopAsyncIteration, asyncio.TimeoutError): + return leading + + async def _collect_events( events: Any, *, max_events: int, timeout: float, + leading: list[pb.MxEvent | ReplayGap] | None = None, ) -> list[pb.MxEvent | ReplayGap]: if max_events > MAX_AGGREGATE_EVENTS: raise click.BadParameter( @@ -1582,7 +1731,7 @@ async def _collect_events( param_hint="--max-events", ) - collected: list[pb.MxEvent | ReplayGap] = [] + collected: list[pb.MxEvent | ReplayGap] = list(leading or []) iterator = events.__aiter__() try: while len(collected) < max_events: diff --git a/clients/python/tests/test_auth_options.py b/clients/python/tests/test_auth_options.py index 53305357..00395be1 100644 --- a/clients/python/tests/test_auth_options.py +++ b/clients/python/tests/test_auth_options.py @@ -9,6 +9,14 @@ from zb_mom_ww_mxgateway import options as options_module from zb_mom_ww_mxgateway.errors import MxGatewayTransportError from zb_mom_ww_mxgateway.options import ClientOptions, create_channel +#: Default HTTP/2 keepalive channel options (30 s ping, 10 s timeout, idle pings). +KEEPALIVE_OPTIONS = [ + ("grpc.keepalive_time_ms", 30_000), + ("grpc.keepalive_timeout_ms", 10_000), + ("grpc.keepalive_permit_without_calls", 1), + ("grpc.http2.max_pings_without_data", 0), +] + def test_auth_metadata_adds_bearer_api_key() -> None: assert auth_metadata("mxgw_test_secret") == ( @@ -70,6 +78,7 @@ def test_create_channel_uses_plaintext_channel(monkeypatch: pytest.MonkeyPatch) [ ("grpc.max_receive_message_length", 16 * 1024 * 1024), ("grpc.max_send_message_length", 16 * 1024 * 1024), + *KEEPALIVE_OPTIONS, ], ), ] @@ -122,6 +131,7 @@ def test_create_channel_uses_tls_channel_tofu_default(monkeypatch: pytest.Monkey [ ("grpc.max_receive_message_length", 16 * 1024 * 1024), ("grpc.max_send_message_length", 16 * 1024 * 1024), + *KEEPALIVE_OPTIONS, ("grpc.ssl_target_name_override", "localhost"), ], ), @@ -171,6 +181,7 @@ def test_create_channel_uses_tls_channel_tofu_respects_server_name_override( [ ("grpc.max_receive_message_length", 16 * 1024 * 1024), ("grpc.max_send_message_length", 16 * 1024 * 1024), + *KEEPALIVE_OPTIONS, # Explicit override from ClientOptions — not the auto-localhost one ("grpc.ssl_target_name_override", "gateway.test"), ], @@ -224,6 +235,7 @@ def test_create_channel_uses_tls_channel_require_cert_validation( [ ("grpc.max_receive_message_length", 16 * 1024 * 1024), ("grpc.max_send_message_length", 16 * 1024 * 1024), + *KEEPALIVE_OPTIONS, ], ), ] @@ -278,6 +290,7 @@ def test_create_channel_uses_tls_channel_ca_file( [ ("grpc.max_receive_message_length", 16 * 1024 * 1024), ("grpc.max_send_message_length", 16 * 1024 * 1024), + *KEEPALIVE_OPTIONS, ], ), ] @@ -324,3 +337,45 @@ def test_tofu_probe_timeout_raises_transport_error( with pytest.raises(MxGatewayTransportError) as excinfo: create_channel(options) assert options.endpoint in str(excinfo.value) + + +def test_keepalive_defaults_are_configurable_and_can_be_disabled() -> None: + from zb_mom_ww_mxgateway.options import ClientOptions + + defaults = ClientOptions(endpoint="localhost:5000") + assert defaults.keepalive_time == 30.0 + assert defaults.keepalive_timeout == 10.0 + assert defaults.keepalive_permit_without_calls is True + + tuned = ClientOptions( + endpoint="localhost:5000", + keepalive_time=45.0, + keepalive_timeout=5.0, + keepalive_permit_without_calls=False, + ) + assert (tuned.keepalive_time, tuned.keepalive_timeout) == (45.0, 5.0) + assert tuned.keepalive_permit_without_calls is False + + with pytest.raises(ValueError): + ClientOptions(endpoint="localhost:5000", keepalive_time=0) + with pytest.raises(ValueError): + ClientOptions(endpoint="localhost:5000", keepalive_timeout=0) + + +def test_keepalive_disabled_adds_no_keepalive_channel_options(monkeypatch) -> None: + from zb_mom_ww_mxgateway import options as options_module + + calls: list[list[tuple[str, object]]] = [] + monkeypatch.setattr( + options_module.grpc.aio, + "insecure_channel", + lambda endpoint, options: calls.append(options) or "plain-channel", + ) + + options_module.create_channel( + options_module.ClientOptions( + endpoint="localhost:5000", plaintext=True, keepalive_time=None + ) + ) + + assert not any(name.startswith("grpc.keepalive") for name, _ in calls[0]) diff --git a/clients/python/tests/test_cli.py b/clients/python/tests/test_cli.py index ae306330..71da4afb 100644 --- a/clients/python/tests/test_cli.py +++ b/clients/python/tests/test_cli.py @@ -973,3 +973,161 @@ def test_stream_events_renders_replay_gap(monkeypatch: pytest.MonkeyPatch) -> No # The gap is rendered, never swallowed, and the normal event still follows it. assert "replayGap" not in rows[1] assert rows[1]["workerSequence"] == "43" + + +def test_batch_reuses_one_client_and_event_loop_across_lines( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """CPY-005: each batch line used to run a new loop and dial a new channel.""" + import asyncio + + connects: list[object] = [] + loops: list[asyncio.AbstractEventLoop] = [] + closes: list[int] = [] + + class _CountingGalaxy(_FakeGalaxyClient): + async def test_connection(self) -> bool: + loops.append(asyncio.get_running_loop()) + return True + + async def close(self) -> None: + closes.append(1) + + fake = _CountingGalaxy(ok=True) + + async def fake_connect(options, **_kwargs): + connects.append(options) + return fake + + monkeypatch.setattr(commands_module.GalaxyRepositoryClient, "connect", fake_connect) + + result = CliRunner().invoke( + main, + ["batch"], + input=("galaxy-test-connection --plaintext --json\n" * 3), + ) + + assert result.exit_code == 0, result.output + assert result.output.count(_BATCH_EOR) == 3 + assert len(connects) == 1, "one channel for all three lines" + assert len(set(map(id, loops))) == 1, "one event loop for all three lines" + assert closes == [1], "the shared client is closed once, when the batch ends" + assert commands_module._batch_context is None + + +def test_batch_dials_separate_clients_for_distinct_connections( + monkeypatch: pytest.MonkeyPatch, +) -> None: + connects: list[str] = [] + + async def fake_connect(options, **_kwargs): + connects.append(options.endpoint) + return _FakeGalaxyClient(ok=True) + + monkeypatch.setattr(commands_module.GalaxyRepositoryClient, "connect", fake_connect) + + result = CliRunner().invoke( + main, + ["batch"], + input=( + "galaxy-test-connection --plaintext --endpoint a:1 --json\n" + "galaxy-test-connection --plaintext --endpoint b:1 --json\n" + "galaxy-test-connection --plaintext --endpoint a:1 --json\n" + ), + ) + + assert result.exit_code == 0, result.output + assert connects == ["a:1", "b:1"] + + +class _SmokeSession: + """Fake session that only delivers an initial event to a subscriber attached before advise.""" + + def __init__(self, *, attach_ack: bool) -> None: + from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb + + self._pb = pb + capabilities = ["stream-events-attached-ack"] if attach_ack else [] + self.open_reply = pb.OpenSessionReply(session_id="s1", capabilities=capabilities) + self.session_id = "s1" + self.calls: list[str] = [] + self.emit_requested: bool | None = None + self._subscribed = False + self._advised = asyncio_event() + + async def __aenter__(self) -> "_SmokeSession": + return self + + async def __aexit__(self, *_exc: object) -> None: + return None + + async def register(self, _name: str) -> int: + self.calls.append("register") + return 1 + + async def add_item(self, _server: int, _item: str) -> int: + self.calls.append("add_item") + return 2 + + async def advise(self, _server: int, _item: int) -> None: + self.calls.append("advise") + self._advised.set() + + def stream_events(self, *, emit_stream_attached: bool = False): + self.calls.append("stream_events") + self.emit_requested = emit_stream_attached + self._subscribed = True + pb = self._pb + + async def _gen(): + if emit_stream_attached: + yield pb.MxEvent(stream_attached=pb.StreamAttached()) + await self._advised.wait() + # The initial value is only delivered to an already-registered subscriber. + yield pb.MxEvent(worker_sequence=7) + + return _gen() + + +def asyncio_event(): + import asyncio + + return asyncio.Event() + + +class _SmokeClient: + def __init__(self, session: _SmokeSession) -> None: + self._session = session + + async def __aenter__(self) -> "_SmokeClient": + return self + + async def __aexit__(self, *_exc: object) -> None: + return None + + async def open_session(self, **_kwargs): + return self._session + + +@pytest.mark.parametrize("attach_ack", [True, False]) +def test_smoke_attaches_event_stream_before_advise( + monkeypatch: pytest.MonkeyPatch, attach_ack: bool +) -> None: + """CPY-006: advising before the stream attaches can lose the initial value.""" + session = _SmokeSession(attach_ack=attach_ack) + + async def fake_connect(options, **_kwargs): + return _SmokeClient(session) + + monkeypatch.setattr(commands_module.GatewayClient, "connect", fake_connect) + + result = CliRunner().invoke( + main, + ["smoke", "--plaintext", "--item", "Tag", "--max-events", "1", "--timeout", "2", "--json"], + ) + + assert result.exit_code == 0, result.output + assert session.calls.index("stream_events") < session.calls.index("advise") + assert session.emit_requested is attach_ack + payload = json.loads(result.output) + assert [event["workerSequence"] for event in payload["events"]] == ["7"] diff --git a/clients/python/tests/test_errors.py b/clients/python/tests/test_errors.py index 36493a2d..e1c2860c 100644 --- a/clients/python/tests/test_errors.py +++ b/clients/python/tests/test_errors.py @@ -3,11 +3,25 @@ import json from pathlib import Path +import grpc import pytest from google.protobuf.json_format import ParseDict -from zb_mom_ww_mxgateway.errors import ensure_mxaccess_success, ensure_protocol_success -from zb_mom_ww_mxgateway import MxAccessError, MxGatewaySessionError +from zb_mom_ww_mxgateway.errors import ( + ensure_mxaccess_success, + ensure_protocol_success, + map_rpc_error, +) +from zb_mom_ww_mxgateway import ( + MxAccessError, + MxGatewayAuthenticationError, + MxGatewayAuthorizationError, + MxGatewayCommandError, + MxGatewaySessionError, + MxGatewayTimeoutError, + MxGatewayTransportError, + MxGatewayUnavailableError, +) from zb_mom_ww_mxgateway.generated import mxaccess_gateway_pb2 as pb FIXTURE_ROOT = Path(__file__).resolve().parents[2] / "proto" / "fixtures" / "behavior" @@ -96,3 +110,59 @@ def test_session_status_maps_to_session_error() -> None: def _load_reply(name: str) -> pb.MxCommandReply: payload = json.loads((FIXTURE_ROOT / name).read_text(encoding="utf-8")) return ParseDict(payload, pb.MxCommandReply()) + + +def test_unknown_enum_values_do_not_replace_typed_errors() -> None: + """CPY-001: proto3 enums are open; an unnamed value must not raise ValueError.""" + reply = pb.MxCommandReply( + protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_MXACCESS_FAILURE), + statuses=[pb.MxStatusProxy(category=99)], + ) + with pytest.raises(MxAccessError) as captured: + ensure_mxaccess_success("write", reply) + assert "category=99" in str(captured.value) + + status = pb.ProtocolStatus(code=999) + with pytest.raises(MxGatewayCommandError) as command_error: + ensure_protocol_success("invoke", status) + assert "999" in str(command_error.value) + + +@pytest.mark.parametrize( + ("code", "expected"), + [ + (grpc.StatusCode.UNAUTHENTICATED, MxGatewayAuthenticationError), + (grpc.StatusCode.PERMISSION_DENIED, MxGatewayAuthorizationError), + (grpc.StatusCode.DEADLINE_EXCEEDED, MxGatewayTimeoutError), + (grpc.StatusCode.UNAVAILABLE, MxGatewayUnavailableError), + (grpc.StatusCode.RESOURCE_EXHAUSTED, MxGatewayUnavailableError), + (grpc.StatusCode.INTERNAL, MxGatewayTransportError), + ], +) +def test_map_rpc_error_preserves_status_code_and_type(code, expected) -> None: + """CPY-003: callers can tell unavailable from deadline-exceeded without __cause__.""" + + class _Error(grpc.RpcError): + def code(self): + return code + + def details(self): + return "boom" + + mapped = map_rpc_error("invoke", _Error()) + + assert type(mapped) is expected + assert mapped.code is code + + +def test_map_rpc_error_redacts_credentials_in_details() -> None: + class _Error(grpc.RpcError): + def code(self): + return grpc.StatusCode.INTERNAL + + def details(self): + return 'bad header "Bearer mxgw_id_secret" key=mxgw_id_secret' + + message = str(map_rpc_error("invoke", _Error())) + + assert "secret" not in message diff --git a/clients/python/tests/test_malformed_reply.py b/clients/python/tests/test_malformed_reply.py index fe8b8a3e..9cee9d7c 100644 --- a/clients/python/tests/test_malformed_reply.py +++ b/clients/python/tests/test_malformed_reply.py @@ -110,3 +110,56 @@ async def test_authenticate_user_echoed_credential_is_scrubbed(fixture: str) -> assert credential not in exc.raw_reply.diagnostic_message for status in exc.raw_reply.statuses: assert credential not in status.diagnostic_text + + +@pytest.mark.parametrize( + ("kind", "call"), + [ + (pb.MX_COMMAND_KIND_REGISTER, lambda s: s.register("client")), + (pb.MX_COMMAND_KIND_ADD_ITEM, lambda s: s.add_item(1, "Tag")), + (pb.MX_COMMAND_KIND_ADD_ITEM2, lambda s: s.add_item2(1, "Tag", "ctx")), + (pb.MX_COMMAND_KIND_SUBSCRIBE_BULK, lambda s: s.subscribe_bulk(1, ["Tag"])), + (pb.MX_COMMAND_KIND_READ_BULK, lambda s: s.read_bulk(1, ["Tag"])), + (pb.MX_COMMAND_KIND_DRAIN_EVENTS, lambda s: s.drain_events(10)), + ], +) +@pytest.mark.asyncio +async def test_handle_and_bulk_helpers_raise_on_reply_without_payload(kind, call) -> None: + """CPY-004: an OK reply with no payload must not read as handle 0 / an empty list.""" + reply = pb.MxCommandReply( + session_id="session-1", + kind=kind, + protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK), + ) + session, _ = await _session_with([reply]) + + with pytest.raises(MalformedReplyError) as captured: + await call(session) + + assert captured.value.raw_reply is reply + + +@pytest.mark.asyncio +async def test_register_falls_back_to_return_value_int32() -> None: + reply = pb.MxCommandReply( + session_id="session-1", + kind=pb.MX_COMMAND_KIND_REGISTER, + protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK), + return_value=pb.MxValue(int32_value=5), + ) + session, _ = await _session_with([reply]) + + assert await session.register("client") == 5 + + +@pytest.mark.asyncio +async def test_empty_bulk_payload_is_a_valid_empty_result() -> None: + reply = pb.MxCommandReply( + session_id="session-1", + kind=pb.MX_COMMAND_KIND_DRAIN_EVENTS, + protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK), + drain_events=pb.DrainEventsReply(), + ) + session, _ = await _session_with([reply]) + + assert await session.drain_events(10) == [] diff --git a/clients/rust/README.md b/clients/rust/README.md index 1c49c9a7..b13788eb 100644 --- a/clients/rust/README.md +++ b/clients/rust/README.md @@ -190,6 +190,21 @@ expected payload surfaces as `Error::MalformedReply`. TLS note: `ClientOptions::with_ca_file` is read asynchronously (`tokio::fs`) during `connect`, so connecting no longer blocks the executor thread. +### HTTP/2 keepalive + +The channel sends an HTTP/2 PING every 30 s, waits 10 s for the +acknowledgement, and pings even while no call is active +(`http2_keep_alive_interval` / `keep_alive_timeout` / +`keep_alive_while_idle(true)`). A half-open connection (firewall idle-out, host +power loss) therefore fails a deadline-less `events()` stream with a transport +error within about 40 s instead of hanging until the gateway's detach grace and +replay retention have expired. Tune with +`ClientOptions::with_keepalive_interval`, `with_keepalive_timeout` and +`with_keepalive_while_idle`, or turn it off with `without_keepalive`. Keep the +interval 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`). + ## Event Streaming And Reconnect-Replay Gaps `session.events()` / `session.events_after(after_worker_sequence)` (and the diff --git a/clients/rust/crates/mxgw-cli/src/batch.rs b/clients/rust/crates/mxgw-cli/src/batch.rs index 5411ed93..2d9744d0 100644 --- a/clients/rust/crates/mxgw-cli/src/batch.rs +++ b/clients/rust/crates/mxgw-cli/src/batch.rs @@ -25,6 +25,9 @@ pub(crate) const BATCH_EOR: &str = "__MXGW_BATCH_EOR__"; /// one worker parked on `ReadFile`; that is acceptable here because no other /// future on the main task needs to run while we wait for the next command. pub(crate) async fn run_batch() -> Result<(), Error> { + // One channel per distinct connection for the whole session, not one per line. + crate::connect::enable_batch_reuse(); + let stdin = io::stdin(); let stdout = io::stdout(); diff --git a/clients/rust/crates/mxgw-cli/src/bench.rs b/clients/rust/crates/mxgw-cli/src/bench.rs index eda3856e..1b70ad2c 100644 --- a/clients/rust/crates/mxgw-cli/src/bench.rs +++ b/clients/rust/crates/mxgw-cli/src/bench.rs @@ -11,6 +11,9 @@ use zb_mom_ww_mxgateway_client::{next_correlation_id, Error}; use crate::cli::*; use crate::connect::*; +/// Pause after a failed `read_bulk` so a down gateway is not retried in a hot loop. +const FAILURE_BACKOFF: Duration = Duration::from_millis(100); + /// Drive the cross-language ReadBulk stress benchmark from Rust: opens its /// own session, subscribes to `bulk_size` tags so the worker's per-session /// value cache populates from real OnDataChange events, hammers ReadBulk in @@ -86,9 +89,14 @@ pub(crate) async fn run_bench_read_bulk( // setup is amortised before the measurement window opens. let warmup_deadline = Instant::now() + Duration::from_secs(warmup_seconds); while Instant::now() < warmup_deadline { - let _ = session + if session .read_bulk(server_handle, tags_ref, timeout_ms_param) - .await; + .await + .is_err() + { + // Back off so a dead gateway is not hammered in a hot loop. + tokio::time::sleep(FAILURE_BACKOFF).await; + } } // Steady-state measurement window: capture per-call latency as @@ -119,7 +127,10 @@ pub(crate) async fn run_bench_read_bulk( } } } - Err(_) => failed_calls += 1, + Err(_) => { + failed_calls += 1; + tokio::time::sleep(FAILURE_BACKOFF).await; + } } } let steady_elapsed = steady_start.elapsed(); diff --git a/clients/rust/crates/mxgw-cli/src/cli.rs b/clients/rust/crates/mxgw-cli/src/cli.rs index 70c757db..332305ef 100644 --- a/clients/rust/crates/mxgw-cli/src/cli.rs +++ b/clients/rust/crates/mxgw-cli/src/cli.rs @@ -543,6 +543,28 @@ pub(crate) struct ConnectionArgs { } impl ConnectionArgs { + /// Identity of the connection for batch-mode client reuse: every field that + /// changes how the channel is dialed, including the API key actually + /// resolved (flag or environment variable). Held in memory only. + pub(crate) fn cache_key(&self) -> String { + let api_key = self + .api_key + .clone() + .or_else(|| env::var(&self.api_key_env).ok()) + .unwrap_or_default(); + format!( + "{}|{}|{}|{:?}|{:?}|{}|{}|{}", + self.endpoint, + api_key, + !self.tls || self.plaintext, + self.ca_file, + self.server_name_override, + self.require_certificate_validation, + self.connect_timeout_seconds, + self.call_timeout_seconds + ) + } + pub(crate) fn options(&self) -> ClientOptions { let mut options = ClientOptions::new(self.endpoint.clone()) .with_plaintext(!self.tls || self.plaintext) diff --git a/clients/rust/crates/mxgw-cli/src/connect.rs b/clients/rust/crates/mxgw-cli/src/connect.rs index 227f67e5..5e0cb732 100644 --- a/clients/rust/crates/mxgw-cli/src/connect.rs +++ b/clients/rust/crates/mxgw-cli/src/connect.rs @@ -1,15 +1,77 @@ //! Gateway and Galaxy client construction helpers. +//! +//! In `batch` mode every command line is dispatched through the same helpers. +//! Dialing a fresh channel per line (TCP + TLS handshake + HTTP/2 settings + CA +//! file read) defeats the point of batch mode, so [`enable_batch_reuse`] turns +//! on a per-process cache that hands out clones of one client per distinct +//! connection. Clones share the underlying channel. + +use std::collections::HashMap; +use std::sync::Mutex; use zb_mom_ww_mxgateway_client::{Error, GalaxyClient, GatewayClient}; use crate::cli::*; +#[derive(Default)] +struct BatchClients { + gateway: HashMap, + galaxy: HashMap, +} + +/// `None` outside batch mode (every command dials its own channel). +static BATCH_CLIENTS: Mutex> = Mutex::new(None); + +/// Reuse one gateway/Galaxy client per distinct connection for the rest of the +/// process. Called once by the batch loop. +pub(crate) fn enable_batch_reuse() { + *BATCH_CLIENTS.lock().expect("batch client cache poisoned") = Some(BatchClients::default()); +} + pub(crate) async fn connect(connection: ConnectionArgs) -> Result { - GatewayClient::connect(connection.options()).await + let key = connection.cache_key(); + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_ref() + { + if let Some(client) = clients.gateway.get(&key) { + return Ok(client.clone()); + } + } + + let client = GatewayClient::connect(connection.options()).await?; + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_mut() + { + clients.gateway.insert(key, client.clone()); + } + Ok(client) } pub(crate) async fn connect_galaxy(connection: ConnectionArgs) -> Result { - GalaxyClient::connect(connection.options()).await + let key = connection.cache_key(); + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_ref() + { + if let Some(client) = clients.galaxy.get(&key) { + return Ok(client.clone()); + } + } + + let client = GalaxyClient::connect(connection.options()).await?; + if let Some(clients) = BATCH_CLIENTS + .lock() + .expect("batch client cache poisoned") + .as_mut() + { + clients.galaxy.insert(key, client.clone()); + } + Ok(client) } pub(crate) async fn session_for( diff --git a/clients/rust/crates/mxgw-cli/src/tests.rs b/clients/rust/crates/mxgw-cli/src/tests.rs index 6beb5144..fc163ee4 100644 --- a/clients/rust/crates/mxgw-cli/src/tests.rs +++ b/clients/rust/crates/mxgw-cli/src/tests.rs @@ -453,3 +453,16 @@ fn alarm_feed_snapshot_status_renders_in_summary_and_json() { let value = crate::events::alarm_feed_message_to_json(&message); assert_eq!(value["snapshotStatus"]["truncated"], true); } + +#[test] +fn batch_cache_key_separates_distinct_connections_and_merges_identical_ones() { + let first = connection_from_ping(&["--endpoint", "http://a:1", "--api-key", "mxgw_x_1"]); + let same = connection_from_ping(&["--endpoint", "http://a:1", "--api-key", "mxgw_x_1"]); + let other_endpoint = + connection_from_ping(&["--endpoint", "http://b:1", "--api-key", "mxgw_x_1"]); + let other_key = connection_from_ping(&["--endpoint", "http://a:1", "--api-key", "mxgw_x_2"]); + + assert_eq!(first.cache_key(), same.cache_key()); + assert_ne!(first.cache_key(), other_endpoint.cache_key()); + assert_ne!(first.cache_key(), other_key.cache_key()); +} diff --git a/clients/rust/src/client.rs b/clients/rust/src/client.rs index f8672e43..9bc51b6c 100644 --- a/clients/rust/src/client.rs +++ b/clients/rust/src/client.rs @@ -21,7 +21,7 @@ use crate::generated::mxaccess_gateway::v1::{ OpenSessionReply, OpenSessionRequest, QueryActiveAlarmsRequest, ReplayGap, StreamAlarmsRequest, StreamEventsRequest, }; -use crate::options::{build_tls_config, ClientOptions}; +use crate::options::{apply_transport_options, build_tls_config, ClientOptions}; use crate::session::Session; /// Generated gateway client wrapped in the auth interceptor that @@ -185,7 +185,7 @@ impl GatewayClient { detail: source.to_string(), } })?; - endpoint = endpoint.connect_timeout(options.connect_timeout()); + endpoint = apply_transport_options(endpoint, &options); if let Some(tls) = build_tls_config(&options).await? { endpoint = endpoint.tls_config(tls)?; diff --git a/clients/rust/src/error.rs b/clients/rust/src/error.rs index 84a6782a..a23a0d85 100644 --- a/clients/rust/src/error.rs +++ b/clients/rust/src/error.rs @@ -174,7 +174,9 @@ impl std::fmt::Display for CommandError { let code = status .and_then(|status| ProtocolStatusCode::try_from(status.code).ok()) .unwrap_or(ProtocolStatusCode::Unspecified); - let message = status.map(|status| status.message.as_str()).unwrap_or(""); + let message = status + .map(|status| redact_credentials(&status.message)) + .unwrap_or_default(); if message.is_empty() { write!(formatter, "{code:?}") @@ -368,39 +370,85 @@ impl Error { name, detail: scrub(&detail), }, - Self::MxAccess(error) => Self::MxAccess(Box::new( - error.with_secrets(secrets.iter().map(|secret| (*secret).to_owned()).collect()), - )), + Self::MxAccess(error) => { + // Scrub the stored reply (so `reply()`/`into_reply()` cannot + // recover an echoed credential) and keep the secrets attached + // for `Display`/`Debug`, together with any attached earlier. + let mut all_secrets = error.secrets.clone(); + all_secrets.extend(secrets.iter().map(|secret| (*secret).to_owned())); + let mut reply = error.into_reply(); + scrub_reply_strings(&mut reply, &all_secrets); + Self::MxAccess(Box::new( + MxAccessError::new(reply).with_secrets(all_secrets), + )) + } + Self::Command(error) => { + let owned: Vec = + secrets.iter().map(|secret| (*secret).to_owned()).collect(); + let mut reply = error.into_reply(); + scrub_reply_strings(&mut reply, &owned); + Self::Command(Box::new(CommandError::new(reply))) + } other => other, } } } +/// Replace every non-empty secret occurrence with `` in the reply's +/// caller-readable string fields — `protocol_status.message`, +/// `diagnostic_message`, and each `statuses[i].diagnostic_text`. A caller +/// reading the structured reply back off an error would otherwise reintroduce +/// the leak that `Display`/`Debug` already close. +pub(crate) fn scrub_reply_strings(reply: &mut MxCommandReply, secrets: &[String]) { + for secret in secrets { + if secret.is_empty() { + continue; + } + if let Some(status) = reply.protocol_status.as_mut() { + status.message = status.message.replace(secret.as_str(), ""); + } + reply.diagnostic_message = reply + .diagnostic_message + .replace(secret.as_str(), ""); + for status in &mut reply.statuses { + status.diagnostic_text = status + .diagnostic_text + .replace(secret.as_str(), ""); + } + } +} + impl From for Error { fn from(status: tonic::Status) -> Self { + // Rebuild the stored status with the redacted message in every arm so + // the `Debug` output and `source()` chain cannot reveal what `Display` + // hides. The original metadata is dropped on purpose: it can carry the + // authorization header value echoed by an intermediary. let message = redact_credentials(status.message()); - match status.code() { + let code = status.code(); + let redacted = || Box::new(tonic::Status::new(code, message.clone())); + match code { Code::Unauthenticated => Self::Authentication { + status: redacted(), message, - status: Box::new(status), }, Code::PermissionDenied => Self::Authorization { + status: redacted(), message, - status: Box::new(status), }, Code::DeadlineExceeded => Self::Timeout { + status: redacted(), message, - status: Box::new(status), }, Code::Cancelled => Self::Cancelled { + status: redacted(), message, - status: Box::new(status), }, Code::Unavailable | Code::ResourceExhausted => Self::Unavailable { + status: redacted(), message, - status: Box::new(status), }, - _ => Self::Status(Box::new(status)), + _ => Self::Status(redacted()), } } } @@ -507,11 +555,31 @@ pub fn ensure_protocol_success( } } +/// Redact credential-shaped text: any `mxgw__` token wherever it +/// appears (quoted, after `key=`, inside parentheses) and the bare word +/// `bearer`. Matching is substring-based on the `mxgw_[A-Za-z0-9_-]+` shape; a +/// whitespace-token prefix test would miss `"mxgw_..."`, `key=mxgw_...` and +/// `(mxgw_...)`. fn redact_credentials(message: &str) -> String { - message + const MARKER: &str = "mxgw_"; + let mut scrubbed = String::with_capacity(message.len()); + let mut rest = message; + while let Some(index) = rest.find(MARKER) { + scrubbed.push_str(&rest[..index]); + scrubbed.push_str(""); + let token = &rest[index..]; + let end = token + .char_indices() + .find(|(_, c)| !(c.is_ascii_alphanumeric() || *c == '_' || *c == '-')) + .map_or(token.len(), |(i, _)| i); + rest = &token[end..]; + } + scrubbed.push_str(rest); + + scrubbed .split_whitespace() .map(|part| { - if part.starts_with("mxgw_") || part.eq_ignore_ascii_case("bearer") { + if part.eq_ignore_ascii_case("bearer") { "" } else { part @@ -533,6 +601,52 @@ mod tests { use tonic::{Code, Status}; + #[test] + fn status_debug_and_display_redact_embedded_key_shapes() { + for text in [ + "bad header \"mxgw_id_secret\"", + "key=mxgw_id_secret", + "(mxgw_id_secret)", + "Bearer mxgw_id_secret", + ] { + for code in [ + Code::Internal, + Code::InvalidArgument, + Code::PermissionDenied, + ] { + let error = Error::from(Status::new(code, text)); + let display = error.to_string(); + let debug = format!("{error:?}"); + assert!(!display.contains("secret"), "{text}: display {display}"); + assert!(!debug.contains("secret"), "{text}: debug {debug}"); + } + } + } + + #[test] + fn redact_secrets_scrubs_command_error_reply() { + let reply = MxCommandReply { + protocol_status: Some(ProtocolStatus { + code: ProtocolStatusCode::InvalidRequest as i32, + message: "bad credential hunter2".to_owned(), + }), + diagnostic_message: "echo hunter2".to_owned(), + ..MxCommandReply::default() + }; + let error = Error::from(Box::new(super::CommandError::new(reply))); + + let error = error.redact_secrets(&["hunter2"]); + + assert!(!error.to_string().contains("hunter2")); + assert!(!format!("{error:?}").contains("hunter2")); + match error { + Error::Command(command) => { + assert!(!command.reply().diagnostic_message.contains("hunter2")); + } + other => panic!("expected Command, got {other:?}"), + } + } + use super::{ensure_mxaccess_success, Error}; use crate::generated::mxaccess_gateway::v1::{ MxCommandReply, MxStatusCategory, MxStatusProxy, ProtocolStatus, ProtocolStatusCode, diff --git a/clients/rust/src/galaxy.rs b/clients/rust/src/galaxy.rs index 794d4b26..123496e4 100644 --- a/clients/rust/src/galaxy.rs +++ b/clients/rust/src/galaxy.rs @@ -22,7 +22,7 @@ use crate::generated::galaxy_repository::v1::{ DiscoverHierarchyRequest, GalaxyObject, GetLastDeployTimeRequest, TestConnectionRequest, WatchDeployEventsRequest, }; -use crate::options::{build_tls_config, ClientOptions}; +use crate::options::{apply_transport_options, build_tls_config, ClientOptions}; const DISCOVER_HIERARCHY_PAGE_SIZE: i32 = 5000; const BROWSE_CHILDREN_PAGE_SIZE: i32 = 500; @@ -180,7 +180,7 @@ impl GalaxyClient { detail: source.to_string(), } })?; - endpoint = endpoint.connect_timeout(options.connect_timeout()); + endpoint = apply_transport_options(endpoint, &options); if let Some(tls) = build_tls_config(&options).await? { endpoint = endpoint.tls_config(tls)?; diff --git a/clients/rust/src/options.rs b/clients/rust/src/options.rs index 7ffb9fde..b632e2cf 100644 --- a/clients/rust/src/options.rs +++ b/clients/rust/src/options.rs @@ -13,10 +13,20 @@ use crate::error::Error; const DEFAULT_MAX_GRPC_MESSAGE_BYTES: usize = 16 * 1024 * 1024; +/// Default HTTP/2 keepalive ping interval. Matches the gateway's permitted +/// client ping rate (30 s); pinging faster makes Kestrel send GOAWAY +/// (`too_many_pings`). +pub const DEFAULT_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30); + +/// Default time to wait for a keepalive ping acknowledgement before the +/// connection is treated as dead. +pub const DEFAULT_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(10); + /// Configuration for connecting to a gateway endpoint. /// /// Defaults are 10s connect timeout, 30s call timeout, no streaming timeout, -/// and plaintext (h2c) transport. Set [`ClientOptions::with_plaintext`] to +/// HTTP/2 keepalive (30s ping, 10s timeout, also while no call is active), and +/// plaintext (h2c) transport. Set [`ClientOptions::with_plaintext`] to /// `false` and supply [`ClientOptions::with_ca_file`] / a server-name override /// for TLS deployments. #[derive(Clone)] @@ -31,6 +41,9 @@ pub struct ClientOptions { call_timeout: Duration, stream_timeout: Option, max_grpc_message_bytes: usize, + keepalive_interval: Option, + keepalive_timeout: Duration, + keepalive_while_idle: bool, } impl ClientOptions { @@ -48,6 +61,9 @@ impl ClientOptions { call_timeout: Duration::from_secs(30), stream_timeout: None, max_grpc_message_bytes: DEFAULT_MAX_GRPC_MESSAGE_BYTES, + keepalive_interval: Some(DEFAULT_KEEPALIVE_INTERVAL), + keepalive_timeout: DEFAULT_KEEPALIVE_TIMEOUT, + keepalive_while_idle: true, } } @@ -128,6 +144,52 @@ impl ClientOptions { self } + /// HTTP/2 keepalive ping interval (default 30 s). Keepalive detects a + /// half-open connection (firewall idle-out, host power loss) so deadline-less + /// streams fail with a transport error instead of hanging forever. Keep this + /// at or above the gateway's permitted client ping interval + /// (`MxGateway:*` keepalive policy, 30 s by default) or the gateway answers + /// with GOAWAY. + pub fn with_keepalive_interval(mut self, interval: Duration) -> Self { + self.keepalive_interval = Some(interval); + self + } + + /// Disable HTTP/2 keepalive pings entirely. + pub fn without_keepalive(mut self) -> Self { + self.keepalive_interval = None; + self + } + + /// Time to wait for a keepalive ping acknowledgement (default 10 s) before + /// the connection is closed. + pub fn with_keepalive_timeout(mut self, timeout: Duration) -> Self { + self.keepalive_timeout = timeout; + self + } + + /// Whether keepalive pings are sent while no call is active (default + /// `true`). Required so an idle channel between calls is still probed. + pub fn with_keepalive_while_idle(mut self, while_idle: bool) -> Self { + self.keepalive_while_idle = while_idle; + self + } + + /// Configured keepalive ping interval; `None` when keepalive is disabled. + pub fn keepalive_interval(&self) -> Option { + self.keepalive_interval + } + + /// Configured keepalive acknowledgement timeout. + pub fn keepalive_timeout(&self) -> Duration { + self.keepalive_timeout + } + + /// Whether keepalive pings are sent while no call is active. + pub fn keepalive_while_idle(&self) -> bool { + self.keepalive_while_idle + } + /// Configured endpoint URL. pub fn endpoint(&self) -> &str { &self.endpoint @@ -180,6 +242,23 @@ impl ClientOptions { } } +/// Apply the connect timeout and HTTP/2 keepalive policy from `options` to an +/// endpoint. Shared by the gateway and Galaxy clients so both channels probe +/// half-open connections the same way. +pub(crate) fn apply_transport_options( + endpoint: tonic::transport::Endpoint, + options: &ClientOptions, +) -> tonic::transport::Endpoint { + let mut endpoint = endpoint.connect_timeout(options.connect_timeout()); + if let Some(interval) = options.keepalive_interval() { + endpoint = endpoint + .http2_keep_alive_interval(interval) + .keep_alive_timeout(options.keepalive_timeout()) + .keep_alive_while_idle(options.keepalive_while_idle()); + } + endpoint +} + /// Where the TLS handshake gets its trust anchors for a given set of options. /// Computed by [`tls_trust_decision`] and applied by [`build_tls_config`]; /// split out so the trust posture is unit-testable without a live handshake. @@ -316,17 +395,43 @@ impl fmt::Debug for ClientOptions { .field("call_timeout", &self.call_timeout) .field("stream_timeout", &self.stream_timeout) .field("max_grpc_message_bytes", &self.max_grpc_message_bytes) + .field("keepalive_interval", &self.keepalive_interval) + .field("keepalive_timeout", &self.keepalive_timeout) + .field("keepalive_while_idle", &self.keepalive_while_idle) .finish() } } #[cfg(test)] mod tests { + use std::time::Duration; + use super::ClientOptions; use crate::auth::ApiKey; use super::{build_tls_config, tls_trust_decision, TlsTrustDecision}; + #[test] + fn keepalive_defaults_match_the_gateway_policy() { + let options = ClientOptions::new("http://localhost:5000"); + + assert_eq!(options.keepalive_interval(), Some(Duration::from_secs(30))); + assert_eq!(options.keepalive_timeout(), Duration::from_secs(10)); + assert!(options.keepalive_while_idle()); + } + + #[test] + fn keepalive_is_configurable_and_can_be_disabled() { + let options = ClientOptions::new("http://localhost:5000") + .with_keepalive_interval(Duration::from_secs(45)) + .with_keepalive_timeout(Duration::from_secs(5)) + .with_keepalive_while_idle(false); + assert_eq!(options.keepalive_interval(), Some(Duration::from_secs(45))); + assert_eq!(options.keepalive_timeout(), Duration::from_secs(5)); + assert!(!options.keepalive_while_idle()); + assert_eq!(options.without_keepalive().keepalive_interval(), None); + } + #[test] fn debug_redacts_api_key() { let options = diff --git a/clients/rust/src/session.rs b/clients/rust/src/session.rs index cc033084..58c8a958 100644 --- a/clients/rust/src/session.rs +++ b/clients/rust/src/session.rs @@ -11,7 +11,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use crate::client::{EventStream, GatewayClient}; -use crate::error::{ensure_protocol_success, Error, MxAccessError}; +use crate::error::{ensure_protocol_success, Error}; use crate::generated::mxaccess_gateway::v1::mx_command::Payload; use crate::generated::mxaccess_gateway::v1::mx_command_reply; use crate::generated::mxaccess_gateway::v1::{ @@ -1209,45 +1209,14 @@ fn string_secret(value: &MxValue) -> Vec { } } -/// Attach caller-supplied exact secrets to an [`Error::MxAccess`] before it -/// propagates. This both scrubs the stored reply's caller-readable string -/// fields (so `reply()`/`into_reply()` cannot recover a credential MXAccess -/// echoed back verbatim) and keeps the secrets on the error as a -/// belt-and-suspenders for `Display`/`Debug`. Any other error variant is -/// returned unchanged. +/// Attach caller-supplied exact secrets to an error before it propagates, so +/// that neither `Display`, `Debug`, `source()` nor the structured reply carried +/// by [`Error::MxAccess`] / [`Error::Command`] can reveal them. Every variant is +/// scrubbed, not only [`Error::MxAccess`]: a worker- or protocol-level status +/// (`WORKER_UNAVAILABLE`, `INVALID_REQUEST`) can echo the credential too. fn attach_secrets(error: Error, secrets: Vec) -> Error { - match error { - Error::MxAccess(boxed) => { - let mut reply = boxed.into_reply(); - scrub_reply_strings(&mut reply, &secrets); - Error::MxAccess(Box::new(MxAccessError::new(reply).with_secrets(secrets))) - } - other => other, - } -} - -/// Replace every non-empty secret occurrence with `` in the reply's -/// caller-readable string fields — `protocol_status.message`, -/// `diagnostic_message`, and each `statuses[i].diagnostic_text`. A caller -/// reading the structured reply back off an [`Error::MxAccess`] would otherwise -/// reintroduce the leak that `Display`/`Debug` already close. -fn scrub_reply_strings(reply: &mut MxCommandReply, secrets: &[String]) { - for secret in secrets { - if secret.is_empty() { - continue; - } - if let Some(status) = reply.protocol_status.as_mut() { - status.message = status.message.replace(secret.as_str(), ""); - } - reply.diagnostic_message = reply - .diagnostic_message - .replace(secret.as_str(), ""); - for status in &mut reply.statuses { - status.diagnostic_text = status - .diagnostic_text - .replace(secret.as_str(), ""); - } - } + let secret_refs: Vec<&str> = secrets.iter().map(String::as_str).collect(); + error.redact_secrets(&secret_refs) } fn suspend_status(reply: MxCommandReply) -> Result { diff --git a/clients/rust/tests/client_behavior.rs b/clients/rust/tests/client_behavior.rs index f72b44e8..b8b70e2a 100644 --- a/clients/rust/tests/client_behavior.rs +++ b/clients/rust/tests/client_behavior.rs @@ -887,6 +887,35 @@ async fn authenticate_user_keeps_credentials_out_of_surfaced_errors() { ); } +#[tokio::test] +async fn authenticate_user_scrubs_credential_from_protocol_level_command_error() { + // CRS-002: a protocol-level failure (not MXACCESS_FAILURE) surfaces as + // Error::Command; its message and diagnostic must be scrubbed too. + let credential = "sup3rSecretVerify9f3a2b"; + let mut reply = command_reply_fixture("authenticate-user.echoed-credential.reply.json"); + reply.protocol_status = Some(ProtocolStatus { + code: ProtocolStatusCode::InvalidRequest as i32, + message: format!("bad request for {credential}"), + }); + reply.diagnostic_message = format!("echo {credential}"); + let state = Arc::new(FakeState::default()); + *state.invoke_override.lock().await = Some(InvokeOverride::CannedReply(Box::new(reply))); + let endpoint = spawn_fake_gateway(state.clone()).await; + let client = GatewayClient::connect(ClientOptions::new(endpoint)) + .await + .unwrap(); + let session = client.session("session-fixture"); + + let error = session + .authenticate_user(7, "verifier", credential) + .await + .unwrap_err(); + + assert!(matches!(error, Error::Command(_)), "{error:?}"); + assert!(!error.to_string().contains(credential)); + assert!(!format!("{error:?}").contains(credential)); +} + #[tokio::test] async fn authenticate_user_scrubs_exact_caller_credential_echoed_in_diagnostic() { // CLI-40: MXAccess can echo the supplied credential back inside its failure