diff --git a/clients/dotnet/DotnetClientDesign.md b/clients/dotnet/DotnetClientDesign.md index 4124f3d4..01630b80 100644 --- a/clients/dotnet/DotnetClientDesign.md +++ b/clients/dotnet/DotnetClientDesign.md @@ -111,6 +111,8 @@ public sealed class MxGatewayClientOptions public string? ServerNameOverride { get; init; } public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10); public TimeSpan DefaultCallTimeout { get; init; } = TimeSpan.FromSeconds(30); + public TimeSpan KeepAlivePingDelay { get; init; } = TimeSpan.FromSeconds(30); + public TimeSpan KeepAlivePingTimeout { get; init; } = TimeSpan.FromSeconds(10); public MxGatewayClientRetryOptions Retry { get; init; } = new(); public ILoggerFactory? LoggerFactory { get; init; } } @@ -118,7 +120,7 @@ public sealed class MxGatewayClientOptions The .NET client applies a bounded Polly retry policy only to idempotent calls: `CloseSession` and diagnostic `Invoke` commands such as `Ping`, -`GetSessionState`, and `GetWorkerInfo`. It does not retry `OpenSession`, event +`GetSessionState`, and `GetWorkerInfo`. Only `Unavailable` and `DeadlineExceeded` are retried. It does not retry `OpenSession`, event streams, writes, secured writes, authentication, registration, item management, or subscription changes because those calls can partially succeed in MXAccess. @@ -157,7 +159,10 @@ The interceptor must redact the key in logs and exceptions. Expose `StreamEventsAsync` as `IAsyncEnumerable`. On cancellation, cancel the gRPC stream and surface `OperationCanceledException` only when the -caller initiated cancellation. +caller initiated cancellation. A server-sent `Cancelled` status becomes +`MxGatewayException`; `NotFound` / `FailedPrecondition` become +`MxGatewaySessionException`. The channel sends HTTP/2 keepalive pings every 30 s +(10 s timeout, also with no active call) so a half-open connection fails the read. Do not reorder events. diff --git a/clients/dotnet/README.md b/clients/dotnet/README.md index 772fa629..89830fd5 100644 --- a/clients/dotnet/README.md +++ b/clients/dotnet/README.md @@ -196,8 +196,35 @@ The attached session's `OpenSessionReply` carries only the session id. worker; call until empty). `DisposeAsync` closes the session best-effort and does not throw when the gateway is unreachable or the client is already disposed. +### Keepalive and errors + +`Create(options)` configures HTTP/2 keepalive on the channel's `SocketsHttpHandler`: +a ping every `KeepAlivePingDelay` (default 30 s) with a `KeepAlivePingTimeout` +(default 10 s), sent even while no call is active (`HttpKeepAlivePingPolicy.Always`). +A server-streaming read otherwise never fails on a half-open connection, so an idle +event stream would hang with no signal. The defaults match the gateway's permitted +client ping interval (`MxGateway:*` keepalive options); a shorter interval makes the +server answer `GOAWAY` "too many pings". Set `KeepAlivePingDelay` to +`Timeout.InfiniteTimeSpan` to disable. A caller-owned channel passed to +`Create(GrpcChannel, ...)` keeps its own handler settings. + +`OperationCanceledException` is raised only when the caller's token is cancelled. +A gateway-sent `Cancelled` status (session closed or killed, gateway shutdown) +raises `MxGatewayException`. `NotFound` / `FailedPrecondition` from a session RPC +raise `MxGatewaySessionException`: reopen the session. Every `MxGatewayException` +that wraps a gRPC failure exposes `GrpcStatusCode`. `Register`, `AddItem` and +`AddItem2` raise `MxGatewayMalformedReplyException` on an OK reply that carries +neither the typed payload nor an int32 `return_value`, instead of returning handle 0. + +`MxGatewaySession.DisposeAsync` makes one bounded (5 s) close attempt and never +throws. Disposing an owned client also disposes its `SocketsHttpHandler` and pinned +CA certificate. `MxGatewayEventStream.DisposeAsync` waits for an in-flight read to +unwind before releasing the call. + Retry applies only to idempotent calls (`CloseSessionRawAsync`, ping, -session-state and worker-info commands, Galaxy reads). `AcknowledgeAlarmAsync` +session-state and worker-info commands, Galaxy reads) and only on `Unavailable` / +`DeadlineExceeded`; `ResourceExhausted` is never retried because it is +deterministic (auth throttle, oversize message). `AcknowledgeAlarmAsync` is never retried because it is a non-idempotent operator write that re-sends the operator password and can double-acknowledge in the Historian. @@ -371,6 +398,16 @@ optionally writes a value when `--type` and `--value` are supplied, reads a bounded event stream, and closes the session in a `finally` block. CLI error output redacts API keys supplied through `--api-key`. +Every command except `stream-events`, `stream-alarms`, `bench-read-bulk`, +`galaxy-watch` and `galaxy-browse` is cancelled after `--timeout` (default 30 s); +those five run until Ctrl+C, their own bound, or an explicit `--timeout`. A +command that times out prints an error line (a JSON error object with `--json`) +and exits 1. `batch` mode reuses one client and channel for consecutive lines whose +connection options are identical. On a failed command only the `--value` / +`--values` of the `write-secured*` commands is redacted, and only as a whole token, +so a short value such as `0` does not garble the HRESULT. +`bench-read-bulk` backs off between failing calls rather than spinning. + ### `authenticate-user` credentials ```powershell diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/CliClientCache.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/CliClientCache.cs new file mode 100644 index 00000000..afefb238 --- /dev/null +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/CliClientCache.cs @@ -0,0 +1,83 @@ +using ZB.MOM.WW.MxGateway.Client; + +namespace ZB.MOM.WW.MxGateway.Client.Cli; + +/// +/// Reuses one CLI client per distinct connection configuration across batch-mode lines so each +/// line does not pay a fresh TCP/TLS/HTTP/2 handshake. Disposing the cache disposes every client. +/// +internal sealed class CliClientCache : IAsyncDisposable +{ + private readonly Dictionary _clients = []; + + /// Gets the cached client for the options' connection settings, creating it on first use. + /// The connection options for this command. + /// Creates a client when none is cached. + /// A lease that does not dispose the shared client. + public Lease Acquire( + MxGatewayClientOptions options, + Func factory) + { + string key = string.Join( + '\n', + options.Endpoint, + options.ApiKey, + options.UseTls, + options.CaCertificatePath, + options.ServerNameOverride, + options.RequireCertificateValidation, + options.ConnectTimeout, + options.DefaultCallTimeout, + options.StreamTimeout, + options.KeepAlivePingDelay, + options.KeepAlivePingTimeout); + + if (!_clients.TryGetValue(key, out IMxGatewayCliClient? client)) + { + client = factory(options); + _clients[key] = client; + } + + return Lease.Shared(client); + } + + /// Disposes every cached client. + /// A task that represents the asynchronous operation. + public async ValueTask DisposeAsync() + { + foreach (IMxGatewayCliClient client in _clients.Values) + { + await client.DisposeAsync().ConfigureAwait(false); + } + + _clients.Clear(); + } + + /// A client handed to one command; disposes it only when the command owns it. + internal sealed class Lease : IAsyncDisposable + { + private readonly bool _owned; + + private Lease(IMxGatewayCliClient client, bool owned) + { + Client = client; + _owned = owned; + } + + /// Gets the leased client. + public IMxGatewayCliClient Client { get; } + + /// Wraps a client the command created and must dispose. + /// The client. + /// The lease. + public static Lease Owned(IMxGatewayCliClient client) => new(client, owned: true); + + /// Wraps a cache-owned client. + /// The client. + /// The lease. + public static Lease Shared(IMxGatewayCliClient client) => new(client, owned: false); + + /// + public ValueTask DisposeAsync() => _owned ? Client.DisposeAsync() : ValueTask.CompletedTask; + } +} diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayCliSecretRedactor.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayCliSecretRedactor.cs index 9f2532c8..acb8b39a 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayCliSecretRedactor.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayCliSecretRedactor.cs @@ -29,4 +29,55 @@ internal static class MxGatewayCliSecretRedactor return redacted; } + + /// + /// Replaces each occurrence of a token only where it stands alone, i.e. it is not adjacent to a + /// letter, digit or underscore. Used for a user-supplied value that may be short: a plain + /// substring replace would corrupt unrelated text (a value of 0 turns + /// 0x80004005 into [redacted]x8[redacted]...). + /// + /// The message text to redact. + /// The secret tokens to remove; null or empty entries are ignored. + /// The value with whole-token occurrences replaced by a redacted placeholder. + public static string RedactTokens(string value, IEnumerable tokens) + { + if (string.IsNullOrEmpty(value) || tokens is null) + { + return value; + } + + string redacted = value; + foreach (string? token in tokens) + { + if (string.IsNullOrEmpty(token)) + { + continue; + } + + System.Text.StringBuilder builder = new(redacted.Length); + int position = 0; + while (position < redacted.Length) + { + int index = redacted.IndexOf(token, position, StringComparison.Ordinal); + if (index < 0) + { + break; + } + + int end = index + token.Length; + bool leftBoundary = index == 0 || !IsWordCharacter(redacted[index - 1]); + bool rightBoundary = end >= redacted.Length || !IsWordCharacter(redacted[end]); + builder.Append(redacted, position, index - position); + builder.Append(leftBoundary && rightBoundary ? "[redacted]" : token); + position = end; + } + + builder.Append(redacted, position, redacted.Length - position); + redacted = builder.ToString(); + } + + return redacted; + } + + private static bool IsWordCharacter(char c) => char.IsLetterOrDigit(c) || c == '_'; } diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs index a345908a..5483de83 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Cli/MxGatewayClientCli.cs @@ -65,7 +65,8 @@ public static class MxGatewayClientCli TextWriter standardError, Func clientFactory, TextReader standardInput, - bool forceJsonErrors = false) + bool forceJsonErrors = false, + CliClientCache? clientCache = null) { if (args.Length is 0 || IsHelp(args[0])) { @@ -95,7 +96,11 @@ public static class MxGatewayClientCli return WriteUnknownCommand(command, standardError); } - await using IMxGatewayCliClient client = clientFactory(CreateOptions(arguments)); + MxGatewayClientOptions clientOptions = CreateOptions(arguments); + await using CliClientCache.Lease lease = clientCache is null + ? CliClientCache.Lease.Owned(clientFactory(clientOptions)) + : clientCache.Acquire(clientOptions, clientFactory); + IMxGatewayCliClient client = lease.Client; using CancellationTokenSource cancellation = CreateCancellation(arguments, command); return command switch @@ -173,7 +178,7 @@ public static class MxGatewayClientCli _ => WriteUnknownCommand(command, standardError), }; } - catch (Exception exception) when (exception is not OperationCanceledException) + catch (Exception exception) { // Redact the *effective* key — from --api-key or the --api-key-env // environment variable — so an env-var-sourced key echoed in a @@ -181,12 +186,24 @@ public static class MxGatewayClientCli // MXAccess credentials (AuthenticateUser password, WriteSecured // payloads) that could otherwise be echoed back in a surfaced error. string? apiKey = TryResolveApiKey(arguments); + string rawMessage = exception is OperationCanceledException + ? $"The command timed out or was cancelled (--timeout {FormatTimeout(arguments)})." + : exception.Message; string message = MxGatewayCliSecretRedactor.Redact( - exception.Message, + rawMessage, apiKey, TryResolveVerifyUserPassword(arguments), - ResolveOperatorPassword(arguments), - arguments.GetOptional("value")); + ResolveOperatorPassword(arguments)); + + // The secured-write payload is the only --value/--values that is a secret. It is + // redacted as a whole token only, so a short value such as "0" does not destroy the + // HRESULT or session id in the same message. + if (IsSecuredWriteCommand(command)) + { + message = MxGatewayCliSecretRedactor.RedactTokens( + message, + SecuredWriteValues(arguments)); + } if (forceJsonErrors || arguments.HasFlag("json")) { @@ -218,6 +235,9 @@ public static class MxGatewayClientCli Func clientFactory, TextReader standardInput) { + // One client (and so one channel) per distinct connection configuration, reused across + // lines instead of a TCP/TLS/HTTP/2 handshake per command (CDN-011). + await using CliClientCache clientCache = new(); while (true) { string? line = await standardInput.ReadLineAsync().ConfigureAwait(false); @@ -247,7 +267,8 @@ public static class MxGatewayClientCli commandError, clientFactory, standardInput, - forceJsonErrors: true) + forceJsonErrors: true, + clientCache: clientCache) .ConfigureAwait(false); } catch (Exception exception) @@ -464,12 +485,35 @@ public static class MxGatewayClientCli + $"--verify-user-password, --verify-user-password-env, {LegacyVerifyPasswordEnvironmentName})."); } + private static string FormatTimeout(CliArguments arguments) + { + string? raw = arguments.GetOptional("timeout"); + return string.IsNullOrWhiteSpace(raw) ? "30s" : raw; + } + + private static bool IsSecuredWriteCommand(string command) => + command is "write-secured" or "write-secured2" or "write-secured-bulk" or "write-secured2-bulk"; + + private static IEnumerable SecuredWriteValues(CliArguments arguments) + { + yield return arguments.GetOptional("value"); + string? values = arguments.GetOptional("values"); + if (values is not null) + { + foreach (string item in values.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) + { + yield return item; + } + } + } + private static CancellationTokenSource CreateCancellation(CliArguments arguments, string command) { var cancellation = new CancellationTokenSource(); // Long-running streaming commands run until Ctrl+C / cancellation by default; // a caller-supplied --timeout still applies if present. - bool isLongRunning = command is "galaxy-watch" or "galaxy-browse"; + bool isLongRunning = command is "galaxy-watch" or "galaxy-browse" or "stream-events" or "stream-alarms" + or "bench-read-bulk"; string? rawTimeout = arguments.GetOptional("timeout"); if (isLongRunning && string.IsNullOrWhiteSpace(rawTimeout)) { @@ -1134,6 +1178,14 @@ public static class MxGatewayClientCli return reply.Register.ServerHandle; } + // A failing ReadBulk returns in microseconds; without a pause the loop would issue failing RPCs + // as fast as the CPU allows and burst-load the gateway when it comes back. + private static Task BenchBackoffAsync(int consecutiveFailures, CancellationToken cancellationToken) + { + int delayMs = Math.Min(1000, 10 * (1 << Math.Min(consecutiveFailures, 7))); + return Task.Delay(delayMs, cancellationToken); + } + /// /// Cross-language stress benchmark for ReadBulk. Opens its own session, /// subscribes to N tags so the worker's MxAccessValueCache populates from @@ -1213,12 +1265,22 @@ public static class MxGatewayClientCli readBulkCommand.TagAddresses.Add(tags); MxCommand readBulkMxCommand = new() { Kind = MxCommandKind.ReadBulk, ReadBulk = readBulkCommand }; + int warmupFailures = 0; while (DateTime.UtcNow < warmupDeadline) { - _ = await client.InvokeAsync( + MxCommandReply warmupReply = await client.InvokeAsync( CreateCommandRequest(sessionId, readBulkMxCommand), cancellationToken) .ConfigureAwait(false); + if (warmupReply.ProtocolStatus?.Code == ProtocolStatusCode.Ok) + { + warmupFailures = 0; + } + else + { + // Warm-up replies are not measured, but a failing one must not spin the CPU. + await BenchBackoffAsync(++warmupFailures, cancellationToken).ConfigureAwait(false); + } } // Steady state — capture per-call wall latency with a high-res @@ -1228,6 +1290,7 @@ public static class MxGatewayClientCli long cachedReadResults = 0; int successfulCalls = 0; int failedCalls = 0; + int consecutiveFailures = 0; DateTime steadyDeadline = DateTime.UtcNow + TimeSpan.FromSeconds(durationSeconds); DateTime steadyStart = DateTime.UtcNow; @@ -1248,6 +1311,7 @@ public static class MxGatewayClientCli sw.Stop(); failedCalls++; latencyMillis.Add(sw.Elapsed.TotalMilliseconds); + await BenchBackoffAsync(++consecutiveFailures, cancellationToken).ConfigureAwait(false); continue; } @@ -1255,9 +1319,11 @@ public static class MxGatewayClientCli if (reply.ProtocolStatus?.Code != ProtocolStatusCode.Ok) { failedCalls++; + await BenchBackoffAsync(++consecutiveFailures, cancellationToken).ConfigureAwait(false); continue; } + consecutiveFailures = 0; successfulCalls++; if (reply.ReadBulk is not null) { diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/FakeGatewayTransport.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/FakeGatewayTransport.cs index 7d027f96..4c52b466 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/FakeGatewayTransport.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/FakeGatewayTransport.cs @@ -112,18 +112,28 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx return Task.FromResult(OpenSessionReply); } + /// + /// Gets or sets an optional behaviour run (before any queued exception) on each CloseSessionAsync call. + /// + public Func? CloseSessionBehavior { get; set; } + /// - public Task CloseSessionAsync( + public async Task CloseSessionAsync( CloseSessionRequest request, CallOptions callOptions) { CloseSessionCalls.Add((request, callOptions)); + if (CloseSessionBehavior is not null) + { + await CloseSessionBehavior(callOptions).ConfigureAwait(false); + } + if (CloseSessionExceptions.TryDequeue(out Exception? exception)) { throw exception; } - return Task.FromResult(CloseSessionReply); + return CloseSessionReply; } /// diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientCliTests.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientCliTests.cs index cdae0366..2f57e4b6 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientCliTests.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientCliTests.cs @@ -1413,8 +1413,7 @@ public sealed class MxGatewayClientCliTests }; var sw = System.Diagnostics.Stopwatch.StartNew(); - await Assert.ThrowsAsync(async () => - await MxGatewayClientCli.RunAsync( + int exitCode = await MxGatewayClientCli.RunAsync( [ "bench-read-bulk", "--endpoint", @@ -1430,9 +1429,13 @@ public sealed class MxGatewayClientCliTests ], output, error, - _ => fakeClient)); + _ => fakeClient); sw.Stop(); + // A cancelled command is reported as an error line and exit code 1, not an unhandled exception (CDN-009). + Assert.Equal(1, exitCode); + Assert.Contains("timed out or was cancelled", error.ToString(), StringComparison.Ordinal); + // Without the fix the loop swallows OCE and continues until the 30 s // steady-state deadline expires. With the fix it exits as soon as OCE // surfaces. Generous 10 s ceiling to keep the test stable under load. @@ -1590,6 +1593,163 @@ public sealed class MxGatewayClientCliTests return tokens.ToArray(); } + /// Verifies batch mode builds one client for lines with identical connection options (CDN-011). + /// A task that represents the asynchronous operation. + [Fact] + public async Task RunAsync_Batch_ReusesOneClientAcrossLines() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + using var input = new StringReader(string.Join( + "\n", + Enumerable.Repeat("close-session --endpoint http://localhost:5000 --api-key k --session-id s", 3)) + "\n"); + int created = 0; + + int exitCode = await MxGatewayClientCli.RunAsync( + ["batch"], + output, + error, + _ => + { + created++; + return new FakeCliClient(); + }, + input); + + Assert.Equal(0, exitCode); + Assert.Equal(1, created); + Assert.Equal(3, output.ToString().Split("__MXGW_BATCH_EOR__").Length - 1); + } + + /// Verifies a different connection configuration gets its own client in batch mode. + /// A task that represents the asynchronous operation. + [Fact] + public async Task RunAsync_Batch_NewClientWhenConnectionOptionsChange() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + using var input = new StringReader( + "close-session --endpoint http://localhost:5000 --api-key k --session-id s\n" + + "close-session --endpoint http://localhost:5001 --api-key k --session-id s\n"); + int created = 0; + + await MxGatewayClientCli.RunAsync( + ["batch"], + output, + error, + _ => + { + created++; + return new FakeCliClient(); + }, + input); + + Assert.Equal(2, created); + } + + /// Verifies a short --value does not garble the HRESULT in the error message (CDN-010). + /// A task that represents the asynchronous operation. + [Fact] + public async Task RunAsync_Write_ShortValue_DoesNotRedactHresult() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + FakeCliClient fakeClient = new(); + fakeClient.InvokeReplies.Enqueue(new MxCommandReply + { + SessionId = "session-fixture", + Kind = MxCommandKind.Write, + ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure }, + Hresult = unchecked((int)0x80004005), + }); + + int exitCode = await MxGatewayClientCli.RunAsync( + [ + "write", + "--endpoint", "http://localhost:5000", + "--api-key", "test-api-key", + "--session-id", "session-fixture", + "--server-handle", "12", + "--item-handle", "34", + "--type", "int32", + "--value", "0", + ], + output, + error, + _ => fakeClient); + + Assert.Equal(1, exitCode); + Assert.Contains("0x80004005", error.ToString(), StringComparison.Ordinal); + } + + /// Verifies a secured-write payload is redacted as a whole token while the HRESULT survives. + /// A task that represents the asynchronous operation. + [Fact] + public async Task RunAsync_WriteSecured_RedactsWholeTokenValueOnly() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + FakeCliClient fakeClient = new() + { + InvokeFailure = new MxGatewayException("rejected 'pa55' (hresult=0x80004005, retry pa55word)"), + }; + + int exitCode = await MxGatewayClientCli.RunAsync( + [ + "write-secured", + "--endpoint", "http://localhost:5000", + "--api-key", "test-api-key", + "--session-id", "session-fixture", + "--server-handle", "12", + "--item-handle", "34", + "--type", "string", + "--value", "pa55", + "--current-user-id", "5", + "--verifier-user-id", "6", + ], + output, + error, + _ => fakeClient); + + Assert.Equal(1, exitCode); + Assert.Equal("rejected '[redacted]' (hresult=0x80004005, retry pa55word)", error.ToString().Trim()); + } + + /// Verifies a command that times out reports an error line and exit code 1 instead of an unhandled exception (CDN-009). + /// A task that represents the asynchronous operation. + [Fact] + public async Task RunAsync_CommandTimeout_ReportsErrorAndExitCodeOne() + { + using var output = new StringWriter(); + using var error = new StringWriter(); + FakeCliClient fakeClient = new() + { + InvokeHandler = async (_, token) => + { + await Task.Delay(Timeout.Infinite, token); + return new MxCommandReply(); + }, + }; + + int exitCode = await MxGatewayClientCli.RunAsync( + [ + "read-bulk", + "--endpoint", "http://localhost:5000", + "--api-key", "test-api-key", + "--session-id", "s", + "--server-handle", "1", + "--items", "A.B", + "--timeout", "100ms", + "--json", + ], + output, + error, + _ => fakeClient); + + Assert.Equal(1, exitCode); + Assert.Contains("timed out", error.ToString(), StringComparison.Ordinal); + } + /// Fake CLI client for testing. private sealed class FakeCliClient : IMxGatewayCliClient { diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientReviewPhase6Tests.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientReviewPhase6Tests.cs new file mode 100644 index 00000000..c8321d49 --- /dev/null +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client.Tests/MxGatewayClientReviewPhase6Tests.cs @@ -0,0 +1,297 @@ +using Grpc.Core; +using ZB.MOM.WW.MxGateway.Contracts.Proto; + +namespace ZB.MOM.WW.MxGateway.Client.Tests; + +/// +/// Regression tests for the 2026-12-02 review, Phase 6: keepalive, error mapping, malformed +/// replies, and stream / channel lifecycle in the .NET client. +/// +public sealed class MxGatewayClientReviewPhase6Tests +{ + /// Verifies the default handler sends HTTP/2 keepalive pings every 30 s, also with no active call (CDN-004). + [Fact] + public void Handler_DefaultsToThirtySecondKeepalive_EvenWithoutActiveCalls() + { + using SocketsHttpHandler handler = MxGatewayClient.CreateHttpHandlerForTests(CreateOptions()); + + Assert.Equal(TimeSpan.FromSeconds(30), handler.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(10), handler.KeepAlivePingTimeout); + Assert.Equal(HttpKeepAlivePingPolicy.Always, handler.KeepAlivePingPolicy); + } + + /// Verifies the keepalive interval and timeout come from the client options on both clients. + [Fact] + public void Handler_HonoursConfiguredKeepalive() + { + MxGatewayClientOptions options = new() + { + Endpoint = new Uri("http://localhost:5000"), + ApiKey = "k", + KeepAlivePingDelay = TimeSpan.FromSeconds(45), + KeepAlivePingTimeout = TimeSpan.FromSeconds(5), + }; + + using SocketsHttpHandler gateway = MxGatewayClient.CreateHttpHandlerForTests(options); + using SocketsHttpHandler galaxy = GalaxyRepositoryClient.CreateHttpHandlerForTests(options); + + Assert.Equal(TimeSpan.FromSeconds(45), gateway.KeepAlivePingDelay); + Assert.Equal(TimeSpan.FromSeconds(5), gateway.KeepAlivePingTimeout); + Assert.Equal(TimeSpan.FromSeconds(45), galaxy.KeepAlivePingDelay); + Assert.Equal(HttpKeepAlivePingPolicy.Always, galaxy.KeepAlivePingPolicy); + } + + /// Verifies non-positive keepalive values are rejected, and an infinite delay disables pings. + [Fact] + public void Options_ValidateKeepalive() + { + Assert.Throws( + () => new MxGatewayClientOptions { Endpoint = new Uri("http://h:1"), ApiKey = "k", KeepAlivePingDelay = TimeSpan.Zero }.Validate()); + Assert.Throws( + () => new MxGatewayClientOptions { Endpoint = new Uri("http://h:1"), ApiKey = "k", KeepAlivePingTimeout = TimeSpan.Zero }.Validate()); + new MxGatewayClientOptions + { + Endpoint = new Uri("http://h:1"), + ApiKey = "k", + KeepAlivePingDelay = Timeout.InfiniteTimeSpan, + }.Validate(); + } + + /// Verifies a gateway-sent Cancelled status is not reported as caller cancellation (CDN-001). + [Fact] + public void Map_CancelledStatusWithLiveToken_IsGatewayExceptionNotCancellation() + { + RpcException rpc = new(new Status(StatusCode.Cancelled, "gateway shutting down")); + + Exception mapped = GrpcStatusMapper.Map(rpc, CancellationToken.None, sessionScoped: true); + + MxGatewayException exception = Assert.IsType(mapped); + Assert.Equal(StatusCode.Cancelled, exception.GrpcStatusCode); + Assert.Same(rpc, exception.InnerException); + } + + /// Verifies the caller's own cancellation still maps to OperationCanceledException. + [Fact] + public void Map_CallerCancelled_IsOperationCanceled() + { + using CancellationTokenSource cts = new(); + cts.Cancel(); + + Exception mapped = GrpcStatusMapper.Map( + new RpcException(new Status(StatusCode.Cancelled, "cancelled")), + cts.Token, + sessionScoped: true); + + Assert.IsType(mapped); + } + + /// Verifies NotFound and FailedPrecondition on the session API become the session-lost exception (CDN-002). + /// The gRPC status the gateway returned. + [Theory] + [InlineData(StatusCode.NotFound)] + [InlineData(StatusCode.FailedPrecondition)] + public void Map_SessionStatuses_AreSessionExceptions(StatusCode code) + { + Exception mapped = GrpcStatusMapper.Map( + new RpcException(new Status(code, "Session x was not found.")), + CancellationToken.None, + sessionScoped: true); + + MxGatewaySessionException exception = Assert.IsType(mapped); + Assert.Equal(code, exception.GrpcStatusCode); + } + + /// Verifies the Galaxy Repository API, which has no sessions, keeps NotFound as a plain gateway exception. + [Fact] + public void Map_NotFoundOnGalaxy_IsPlainGatewayException() + { + Exception mapped = GrpcStatusMapper.Map( + new RpcException(new Status(StatusCode.NotFound, "nope")), + CancellationToken.None, + sessionScoped: false); + + Assert.Equal(typeof(MxGatewayException), mapped.GetType()); + } + + /// Verifies ResourceExhausted is not retried (CDN-007). + /// A task that represents the asynchronous operation. + [Fact] + public async Task CloseSession_ResourceExhausted_IsAttemptedOnce() + { + FakeGatewayTransport transport = CreateTransport(); + transport.CloseSessionExceptions.Enqueue(new MxGatewayResourceExhaustedException( + "limit", + reason: null, + new RpcException(new Status(StatusCode.ResourceExhausted, "limit")))); + transport.CloseSessionExceptions.Enqueue(new MxGatewayResourceExhaustedException( + "limit", + reason: null, + new RpcException(new Status(StatusCode.ResourceExhausted, "limit")))); + await using MxGatewayClient client = new(transport.Options, transport); + + await Assert.ThrowsAsync( + () => client.CloseSessionRawAsync(new CloseSessionRequest { SessionId = "s" })); + + Assert.Single(transport.CloseSessionCalls); + } + + /// Verifies Unavailable is still retried. + /// A task that represents the asynchronous operation. + [Fact] + public async Task CloseSession_Unavailable_IsStillRetried() + { + FakeGatewayTransport transport = CreateTransport(); + transport.CloseSessionExceptions.Enqueue(new MxGatewayException( + "down", + new RpcException(new Status(StatusCode.Unavailable, "down")))); + await using MxGatewayClient client = new(transport.Options, transport); + + await client.CloseSessionRawAsync(new CloseSessionRequest { SessionId = "s" }); + + Assert.Equal(2, transport.CloseSessionCalls.Count); + } + + /// Verifies an OK reply without the typed payload is a protocol error, not handle 0 (CDN-008). + /// The command kind whose reply omits its payload. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData(MxCommandKind.Register)] + [InlineData(MxCommandKind.AddItem)] + [InlineData(MxCommandKind.AddItem2)] + public async Task HandleReturningCommands_MissingPayload_ThrowMalformedReply(MxCommandKind kind) + { + FakeGatewayTransport transport = CreateTransport(); + transport.AddInvokeReply(new MxCommandReply + { + SessionId = "session-fixture", + Kind = kind, + ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, + }); + await using MxGatewayClient client = new(transport.Options, transport); + MxGatewaySession session = await client.OpenSessionAsync(); + + await Assert.ThrowsAsync(async () => + { + _ = kind switch + { + MxCommandKind.Register => await session.RegisterAsync("c"), + MxCommandKind.AddItem => await session.AddItemAsync(1, "Tag.A"), + _ => await session.AddItem2Async(1, "Tag.A", "ctx"), + }; + }); + } + + /// Verifies an int32 return_value is still accepted when the typed payload is absent. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Register_ReturnValueOnly_ResolvesReturnValue() + { + FakeGatewayTransport transport = CreateTransport(); + transport.AddInvokeReply(new MxCommandReply + { + SessionId = "session-fixture", + Kind = MxCommandKind.Register, + ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, + ReturnValue = new MxValue { Int32Value = 9 }, + }); + await using MxGatewayClient client = new(transport.Options, transport); + MxGatewaySession session = await client.OpenSessionAsync(); + + Assert.Equal(9, await session.RegisterAsync("c")); + } + + /// Verifies disposing an event stream while a read is in flight neither throws nor hangs (CDN-003). + /// A task that represents the asynchronous operation. + [Fact] + public async Task EventStream_DisposeWhileReadInFlight_DoesNotThrow() + { + for (int i = 0; i < 50; i++) + { + MxGatewayEventStream stream = await MxGatewayEventStream.OpenAsync( + OpenAttachedThenBlock, + "s", + attachTimeout: null, + CancellationToken.None); + + Task reader = Task.Run(async () => + { + await foreach (MxEvent unused in stream.ReadAllAsync()) + { + } + }); + await Task.Delay(5); + + await stream.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(10)); + + await Assert.ThrowsAnyAsync(() => reader); + } + } + + /// Verifies the dispose-time session close is bounded and swallows cancellation (CDN-005). + /// A task that represents the asynchronous operation. + [Fact] + public async Task SessionDispose_WhenCloseNeverCompletes_ReturnsWithinBound() + { + FakeGatewayTransport transport = CreateTransport(); + transport.CloseSessionBehavior = callOptions => Task.Delay(Timeout.Infinite, callOptions.CancellationToken); + await using MxGatewayClient client = new(transport.Options, transport); + MxGatewaySession session = await client.OpenSessionAsync(); + + await session.DisposeAsync().AsTask().WaitAsync(TimeSpan.FromSeconds(20)); + + Assert.NotEmpty(transport.CloseSessionCalls); + } + + /// Verifies a cancellation surfaced by the close does not escape dispose. + /// A task that represents the asynchronous operation. + [Fact] + public async Task SessionDispose_WhenCloseThrowsCancellation_DoesNotThrow() + { + FakeGatewayTransport transport = CreateTransport(); + transport.CloseSessionExceptions.Enqueue(new OperationCanceledException()); + await using MxGatewayClient client = new(transport.Options, transport); + MxGatewaySession session = await client.OpenSessionAsync(); + + await session.DisposeAsync(); + } + + /// Verifies disposing an owned client closes the connection to the gateway (CDN-006). + /// A task that represents the asynchronous operation. + [Fact] + public async Task Dispose_OwnedClient_DisposesHandler() + { + await using WireFakeGatewayServer server = await WireFakeGatewayServer.StartAsync(); + MxGatewayClient client = server.CreateClient("mxgw_k_s"); + await client.OpenSessionAsync(); + System.Reflection.FieldInfo channelField = typeof(MxGatewayClient).GetField( + "_channel", + System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!; + Grpc.Net.Client.GrpcChannel channel = (Grpc.Net.Client.GrpcChannel)channelField.GetValue(client)!; + + await client.DisposeAsync(); + + // GrpcChannel with DisposeHttpClient disposes the handler; the channel's HttpInvoker is then unusable. + object invoker = typeof(Grpc.Net.Client.GrpcChannel) + .GetProperty("HttpInvoker", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! + .GetValue(channel)!; + await Assert.ThrowsAsync( + () => ((HttpMessageInvoker)invoker).SendAsync( + new HttpRequestMessage(HttpMethod.Get, server.Endpoint), + CancellationToken.None)); + } + + private static async IAsyncEnumerable OpenAttachedThenBlock( + [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken) + { + yield return new MxEvent { StreamAttached = new StreamAttached() }; + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + } + + private static MxGatewayClientOptions CreateOptions() => new() + { + Endpoint = new Uri("http://localhost:5000"), + ApiKey = "k", + }; + + private static FakeGatewayTransport CreateTransport() => new(CreateOptions()); +} diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GalaxyRepositoryClient.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GalaxyRepositoryClient.cs index 35937b80..2116de67 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GalaxyRepositoryClient.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GalaxyRepositoryClient.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Logging; using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy; using Polly; using System.Net.Http; -using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Cryptography.X509Certificates; @@ -25,6 +24,7 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable private readonly bool _ownsChannel; private readonly IGalaxyRepositoryClientTransport _transport; private readonly ResiliencePipeline _safeUnaryRetryPipeline; + private readonly X509Certificate2? _ownedCertificate; private bool _disposed; /// @@ -50,10 +50,12 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable private GalaxyRepositoryClient( GrpcChannel channel, IGalaxyRepositoryClientTransport transport, - bool ownsChannel) + bool ownsChannel, + X509Certificate2? ownedCertificate = null) { _channel = channel; _ownsChannel = ownsChannel; + _ownedCertificate = ownedCertificate; _transport = transport; Options = transport.Options; _safeUnaryRetryPipeline = MxGatewayClientRetryPolicy.Create( @@ -83,12 +85,15 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable ArgumentNullException.ThrowIfNull(options); options.Validate(); - HttpMessageHandler handler = CreateHttpHandler(options); + SocketsHttpHandler handler = GatewayHttpHandlerFactory.Create(options, out X509Certificate2? trustedRoot); var channel = GrpcChannel.ForAddress( options.Endpoint, new GrpcChannelOptions { HttpHandler = handler, + // The channel owns this handler (CDN-006): disposing the channel must also close + // its connection pool, otherwise every recreated client leaks a handler. + DisposeHttpClient = true, LoggerFactory = options.LoggerFactory, MaxReceiveMessageSize = options.MaxGrpcMessageBytes, MaxSendMessageSize = options.MaxGrpcMessageBytes, @@ -99,7 +104,8 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable new GrpcGalaxyRepositoryClientTransport( options, new GalaxyRepository.GalaxyRepositoryClient(channel)), - ownsChannel: true); + ownsChannel: true, + ownedCertificate: trustedRoot); } /// @@ -467,6 +473,7 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable if (_ownsChannel) { _channel?.Dispose(); + _ownedCertificate?.Dispose(); } return ValueTask.CompletedTask; @@ -529,60 +536,13 @@ public sealed class GalaxyRepositoryClient : IAsyncDisposable .ConfigureAwait(false); } - private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options) => - CreateHttpHandlerForTests(options); - - /// Creates the used for gRPC calls, exposed for test configuration. - /// The client options supplying TLS and timeout settings. - /// The configured HTTP handler. - internal static SocketsHttpHandler CreateHttpHandlerForTests(MxGatewayClientOptions options) - { - SocketsHttpHandler handler = new() - { - ConnectTimeout = options.ConnectTimeout, - }; - - if (options.UseTls) - { - handler.SslOptions = new SslClientAuthenticationOptions(); - if (!string.IsNullOrWhiteSpace(options.ServerNameOverride)) - { - handler.SslOptions.TargetHost = options.ServerNameOverride; - } - - if (!string.IsNullOrWhiteSpace(options.CaCertificatePath)) - { - X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath); - handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) => - { - if ((errors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0) - { - return false; - } - - if (certificate is null) - { - return false; - } - - using X509Chain customChain = new(); - customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; - customChain.ChainPolicy.CustomTrustStore.Add(trustedRoot); - customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; - customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; - X509Certificate2 certificateToValidate = certificate as X509Certificate2 - ?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert)); - return customChain.Build(certificateToValidate); - }; - } - else if (!options.RequireCertificateValidation) - { - handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true; - } - } - - return handler; - } + /// + /// Creates the used for gRPC calls; exposed internally so tests can inspect it. + /// + /// The client options that configure connect timeout, keepalive, and TLS behavior. + /// A configured . + internal static SocketsHttpHandler CreateHttpHandlerForTests(MxGatewayClientOptions options) => + GatewayHttpHandlerFactory.Create(options, out _); private void ThrowIfDisposed() { diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GatewayHttpHandlerFactory.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GatewayHttpHandlerFactory.cs new file mode 100644 index 00000000..ea92e783 --- /dev/null +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GatewayHttpHandlerFactory.cs @@ -0,0 +1,81 @@ +using System.Net.Http; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; + +namespace ZB.MOM.WW.MxGateway.Client; + +/// +/// Builds the shared by and +/// : connect timeout, HTTP/2 keepalive, and TLS pinning. +/// +internal static class GatewayHttpHandlerFactory +{ + /// + /// Creates the handler for an owned channel. + /// + /// The client options supplying keepalive, connect timeout, and TLS settings. + /// + /// The pinned CA certificate captured by the validation callback, or when none is pinned. + /// The caller disposes it after the handler is disposed. + /// + /// The configured handler. + public static SocketsHttpHandler Create(MxGatewayClientOptions options, out X509Certificate2? trustedRoot) + { + trustedRoot = null; + + // HTTP/2 keepalive (D7): a server-streaming call only reads, so on a half-open connection + // nothing would ever fail the pending read. Pings are sent while no call is active too + // (Always), because an idle event stream is exactly the case to detect. + SocketsHttpHandler handler = new() + { + ConnectTimeout = options.ConnectTimeout, + KeepAlivePingDelay = options.KeepAlivePingDelay, + KeepAlivePingTimeout = options.KeepAlivePingTimeout, + KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, + }; + + if (!options.UseTls) + { + return handler; + } + + handler.SslOptions = new SslClientAuthenticationOptions(); + if (!string.IsNullOrWhiteSpace(options.ServerNameOverride)) + { + handler.SslOptions.TargetHost = options.ServerNameOverride; + } + + if (!string.IsNullOrWhiteSpace(options.CaCertificatePath)) + { + X509Certificate2 root = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath); + trustedRoot = root; + handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) => + { + if ((errors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) + { + return false; + } + + if (certificate is null) + { + return false; + } + + using X509Chain customChain = new(); + customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + customChain.ChainPolicy.CustomTrustStore.Add(root); + customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; + X509Certificate2 certificateToValidate = certificate as X509Certificate2 + ?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert)); + return customChain.Build(certificateToValidate); + }; + } + else if (!options.RequireCertificateValidation) + { + handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true; + } + + return handler; + } +} diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcGalaxyRepositoryClientTransport.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcGalaxyRepositoryClientTransport.cs index e533db2f..7a122f9e 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcGalaxyRepositoryClientTransport.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcGalaxyRepositoryClientTransport.cs @@ -144,23 +144,6 @@ internal sealed class GrpcGalaxyRepositoryClientTransport( RpcException exception, CancellationToken cancellationToken) { - if (cancellationToken.IsCancellationRequested || exception.StatusCode == StatusCode.Cancelled) - { - return new OperationCanceledException( - exception.Status.Detail, - exception, - cancellationToken); - } - - return exception.StatusCode switch - { - StatusCode.Unauthenticated => new MxGatewayAuthenticationException( - exception.Status.Detail, - innerException: exception), - StatusCode.PermissionDenied => new MxGatewayAuthorizationException( - exception.Status.Detail, - innerException: exception), - _ => new MxGatewayException(exception.Status.Detail, exception), - }; + return GrpcStatusMapper.Map(exception, cancellationToken, sessionScoped: false); } } diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs index 0a9f6b52..f833e248 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcMxGatewayClientTransport.cs @@ -239,27 +239,6 @@ internal sealed class GrpcMxGatewayClientTransport( RpcException exception, CancellationToken cancellationToken) { - if (cancellationToken.IsCancellationRequested || exception.StatusCode == StatusCode.Cancelled) - { - return new OperationCanceledException( - exception.Status.Detail, - exception, - cancellationToken); - } - - return exception.StatusCode switch - { - StatusCode.Unauthenticated => new MxGatewayAuthenticationException( - exception.Status.Detail, - innerException: exception), - StatusCode.PermissionDenied => new MxGatewayAuthorizationException( - exception.Status.Detail, - innerException: exception), - StatusCode.ResourceExhausted => new MxGatewayResourceExhaustedException( - exception.Status.Detail, - MxGatewayResourceExhaustedException.ReadReason(exception), - exception), - _ => new MxGatewayException(exception.Status.Detail, exception), - }; + return GrpcStatusMapper.Map(exception, cancellationToken, sessionScoped: true); } } diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcStatusMapper.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcStatusMapper.cs new file mode 100644 index 00000000..e42911be --- /dev/null +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/GrpcStatusMapper.cs @@ -0,0 +1,53 @@ +using Grpc.Core; + +namespace ZB.MOM.WW.MxGateway.Client; + +/// +/// Maps a transport-level to the client's exception types. Shared by +/// the session and Galaxy Repository transports so the two cannot drift apart. +/// +internal static class GrpcStatusMapper +{ + /// + /// Maps . The original gRPC status stays reachable through + /// and the inner exception. + /// + /// The gRPC failure. + /// The caller's token. + /// + /// for the session API, where NotFound / FailedPrecondition + /// mean the session is gone or not ready; the Galaxy Repository has no sessions. + /// + /// The exception to throw. + public static Exception Map(RpcException exception, CancellationToken cancellationToken, bool sessionScoped) + { + // Only the caller's own cancellation is an OperationCanceledException. A Cancelled status + // with a live token was produced by the gateway (session closed or killed, gateway + // shutdown) and must not be swallowed by `catch (OperationCanceledException)` shutdown code. + if (cancellationToken.IsCancellationRequested) + { + return new OperationCanceledException( + exception.Status.Detail, + exception, + cancellationToken); + } + + return exception.StatusCode switch + { + StatusCode.Unauthenticated => new MxGatewayAuthenticationException( + exception.Status.Detail, + innerException: exception), + StatusCode.PermissionDenied => new MxGatewayAuthorizationException( + exception.Status.Detail, + innerException: exception), + StatusCode.ResourceExhausted => new MxGatewayResourceExhaustedException( + exception.Status.Detail, + MxGatewayResourceExhaustedException.ReadReason(exception), + exception), + StatusCode.NotFound or StatusCode.FailedPrecondition when sessionScoped => new MxGatewaySessionException( + exception.Status.Detail, + innerException: exception), + _ => new MxGatewayException(exception.Status.Detail, exception), + }; + } +} diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs index 744a1214..b639c019 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClient.cs @@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging; using ZB.MOM.WW.MxGateway.Contracts.Proto; using Polly; using System.Net.Http; -using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace ZB.MOM.WW.MxGateway.Client; @@ -18,6 +17,7 @@ public sealed class MxGatewayClient : IAsyncDisposable private readonly bool _ownsChannel; private readonly IMxGatewayClientTransport _transport; private readonly ResiliencePipeline _safeUnaryRetryPipeline; + private readonly X509Certificate2? _ownedCertificate; private bool _disposed; /// @@ -43,10 +43,12 @@ public sealed class MxGatewayClient : IAsyncDisposable private MxGatewayClient( GrpcChannel channel, IMxGatewayClientTransport transport, - bool ownsChannel) + bool ownsChannel, + X509Certificate2? ownedCertificate = null) { _channel = channel; _ownsChannel = ownsChannel; + _ownedCertificate = ownedCertificate; _transport = transport; Options = transport.Options; _safeUnaryRetryPipeline = MxGatewayClientRetryPolicy.Create( @@ -76,12 +78,15 @@ public sealed class MxGatewayClient : IAsyncDisposable ArgumentNullException.ThrowIfNull(options); options.Validate(); - HttpMessageHandler handler = CreateHttpHandler(options); + SocketsHttpHandler handler = GatewayHttpHandlerFactory.Create(options, out X509Certificate2? trustedRoot); var channel = GrpcChannel.ForAddress( options.Endpoint, new GrpcChannelOptions { HttpHandler = handler, + // The channel owns this handler (CDN-006): disposing the channel must also close + // its connection pool, otherwise every recreated client leaks a handler. + DisposeHttpClient = true, LoggerFactory = options.LoggerFactory, MaxReceiveMessageSize = options.MaxGrpcMessageBytes, MaxSendMessageSize = options.MaxGrpcMessageBytes, @@ -92,7 +97,8 @@ public sealed class MxGatewayClient : IAsyncDisposable new GrpcMxGatewayClientTransport( options, new MxAccessGateway.MxAccessGatewayClient(channel)), - ownsChannel: true); + ownsChannel: true, + ownedCertificate: trustedRoot); } /// @@ -325,6 +331,7 @@ public sealed class MxGatewayClient : IAsyncDisposable if (_ownsChannel) { _channel?.Dispose(); + _ownedCertificate?.Dispose(); } return ValueTask.CompletedTask; @@ -387,62 +394,13 @@ public sealed class MxGatewayClient : IAsyncDisposable .ConfigureAwait(false); } - private static HttpMessageHandler CreateHttpHandler(MxGatewayClientOptions options) => - CreateHttpHandlerForTests(options); - /// /// Creates the used for gRPC calls; exposed internally so tests can inspect it. /// - /// The client options that configure connect timeout and TLS behavior. + /// The client options that configure connect timeout, keepalive, and TLS behavior. /// A configured . - internal static SocketsHttpHandler CreateHttpHandlerForTests(MxGatewayClientOptions options) - { - SocketsHttpHandler handler = new() - { - ConnectTimeout = options.ConnectTimeout, - }; - - if (options.UseTls) - { - handler.SslOptions = new SslClientAuthenticationOptions(); - if (!string.IsNullOrWhiteSpace(options.ServerNameOverride)) - { - handler.SslOptions.TargetHost = options.ServerNameOverride; - } - - if (!string.IsNullOrWhiteSpace(options.CaCertificatePath)) - { - X509Certificate2 trustedRoot = X509CertificateLoader.LoadCertificateFromFile(options.CaCertificatePath); - handler.SslOptions.RemoteCertificateValidationCallback = (_, certificate, chain, errors) => - { - if ((errors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) != 0) - { - return false; - } - - if (certificate is null) - { - return false; - } - - using X509Chain customChain = new(); - customChain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; - customChain.ChainPolicy.CustomTrustStore.Add(trustedRoot); - customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; - customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag; - X509Certificate2 certificateToValidate = certificate as X509Certificate2 - ?? X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert)); - return customChain.Build(certificateToValidate); - }; - } - else if (!options.RequireCertificateValidation) - { - handler.SslOptions.RemoteCertificateValidationCallback = (_, _, _, _) => true; - } - } - - return handler; - } + internal static SocketsHttpHandler CreateHttpHandlerForTests(MxGatewayClientOptions options) => + GatewayHttpHandlerFactory.Create(options, out _); private void ThrowIfDisposed() { diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientOptions.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientOptions.cs index df93c3b3..5a2f9360 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientOptions.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientOptions.cs @@ -45,6 +45,20 @@ public sealed class MxGatewayClientOptions /// public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10); + /// + /// Gets the interval between HTTP/2 keepalive pings (default 30 s). Pings are sent even when no + /// call is active, so a half-open connection under an idle event stream is detected. Must stay + /// at or above the gateway's permitted client ping interval (30 s by default) or the server + /// answers with GOAWAY "too many pings". Use to disable. + /// + public TimeSpan KeepAlivePingDelay { get; init; } = TimeSpan.FromSeconds(30); + + /// + /// Gets how long to wait for a keepalive ping acknowledgement before the connection is + /// considered dead and in-flight calls fail (default 10 s). + /// + public TimeSpan KeepAlivePingTimeout { get; init; } = TimeSpan.FromSeconds(10); + /// /// Gets the default timeout for unary gRPC calls. /// @@ -101,6 +115,20 @@ public sealed class MxGatewayClientOptions "The connect timeout must be greater than zero."); } + if (KeepAlivePingDelay != Timeout.InfiniteTimeSpan && KeepAlivePingDelay <= TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException( + nameof(KeepAlivePingDelay), + "The keepalive ping delay must be greater than zero, or Timeout.InfiniteTimeSpan to disable."); + } + + if (KeepAlivePingTimeout <= TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException( + nameof(KeepAlivePingTimeout), + "The keepalive ping timeout must be greater than zero."); + } + if (DefaultCallTimeout <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException( diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientRetryPolicy.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientRetryPolicy.cs index cf1c3dfd..70559224 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientRetryPolicy.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayClientRetryPolicy.cs @@ -86,8 +86,10 @@ internal static class MxGatewayClientRetryPolicy private static bool IsTransientStatus(StatusCode statusCode) { + // ResourceExhausted is deliberately not retried: every source of it on a retried call is + // deterministic over the retry window (the auth-failure throttle, an oversize message), + // so a retry only repeats the work and feeds the throttle (CDN-007). return statusCode is StatusCode.Unavailable - or StatusCode.DeadlineExceeded - or StatusCode.ResourceExhausted; + or StatusCode.DeadlineExceeded; } } diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayEventStream.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayEventStream.cs index 83ec5b3b..184aa7aa 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayEventStream.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayEventStream.cs @@ -18,6 +18,10 @@ public sealed class MxGatewayEventStream : IAsyncDisposable { private readonly IAsyncEnumerator _enumerator; private readonly CancellationTokenSource _lifetime; + // Held for the duration of each MoveNextAsync. An async iterator cannot be disposed while a + // MoveNext is in flight, so DisposeAsync takes the gate (after cancelling) to wait for the + // cancelled read to unwind before it disposes the enumerator (CDN-003). + private readonly SemaphoreSlim _readGate = new(1, 1); private int _readStarted; private int _disposed; @@ -56,9 +60,30 @@ public sealed class MxGatewayEventStream : IAsyncDisposable static state => ((CancellationTokenSource)state!).Cancel(), _lifetime); - while (await _enumerator.MoveNextAsync().ConfigureAwait(false)) + while (true) { - yield return _enumerator.Current; + MxEvent current; + await _readGate.WaitAsync(CancellationToken.None).ConfigureAwait(false); + try + { + if (Volatile.Read(ref _disposed) != 0) + { + throw new OperationCanceledException("The event stream was disposed."); + } + + if (!await _enumerator.MoveNextAsync().ConfigureAwait(false)) + { + yield break; + } + + current = _enumerator.Current; + } + finally + { + _readGate.Release(); + } + + yield return current; } } @@ -72,6 +97,9 @@ public sealed class MxGatewayEventStream : IAsyncDisposable } await _lifetime.CancelAsync().ConfigureAwait(false); + + // Wait for an in-flight read (cancelled above) to unwind; its outcome belongs to the reader. + await _readGate.WaitAsync(CancellationToken.None).ConfigureAwait(false); try { await _enumerator.DisposeAsync().ConfigureAwait(false); @@ -79,6 +107,7 @@ public sealed class MxGatewayEventStream : IAsyncDisposable finally { _lifetime.Dispose(); + _readGate.Release(); } } diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayException.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayException.cs index 79b4b277..f2eeb1c6 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayException.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewayException.cs @@ -55,6 +55,13 @@ public class MxGatewayException : Exception Statuses = statuses; } + /// + /// Gets the gRPC status code of the failed call when this exception wraps an + /// , otherwise . Lets a caller tell + /// "deadline exceeded" from "gateway unavailable" without digging into the inner exception. + /// + public Grpc.Core.StatusCode? GrpcStatusCode => (InnerException as Grpc.Core.RpcException)?.StatusCode; + /// /// Gets the session ID associated with the exception, if available. /// diff --git a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs index 2afac9ef..b560acf8 100644 --- a/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs +++ b/clients/dotnet/ZB.MOM.WW.MxGateway.Client/MxGatewaySession.cs @@ -10,6 +10,8 @@ namespace ZB.MOM.WW.MxGateway.Client; public sealed class MxGatewaySession : IAsyncDisposable { private readonly MxGatewayClient _client; + private static readonly TimeSpan DisposeCloseTimeout = TimeSpan.FromSeconds(5); + private readonly SemaphoreSlim _closeLock = new(1, 1); private CloseSessionReply? _closeReply; @@ -81,7 +83,7 @@ public sealed class MxGatewaySession : IAsyncDisposable MxCommandReply reply = await RegisterRawAsync(clientName, cancellationToken) .ConfigureAwait(false); reply.EnsureProtocolSuccess().EnsureMxAccessSuccess(); - return reply.Register?.ServerHandle ?? reply.ReturnValue.Int32Value; + return ResolveInt32Result(reply.Register?.ServerHandle, reply, "Register"); } /// @@ -123,7 +125,7 @@ public sealed class MxGatewaySession : IAsyncDisposable cancellationToken) .ConfigureAwait(false); reply.EnsureProtocolSuccess().EnsureMxAccessSuccess(); - return reply.AddItem?.ItemHandle ?? reply.ReturnValue.Int32Value; + return ResolveInt32Result(reply.AddItem?.ItemHandle, reply, "AddItem"); } /// @@ -174,7 +176,7 @@ public sealed class MxGatewaySession : IAsyncDisposable cancellationToken) .ConfigureAwait(false); reply.EnsureProtocolSuccess().EnsureMxAccessSuccess(); - return reply.AddItem2?.ItemHandle ?? reply.ReturnValue.Int32Value; + return ResolveInt32Result(reply.AddItem2?.ItemHandle, reply, "AddItem2"); } /// @@ -1717,9 +1719,12 @@ public sealed class MxGatewaySession : IAsyncDisposable { try { - await CloseAsync().ConfigureAwait(false); + // Bounded (CDN-005): the retried close would otherwise hold `await using` for about + // two full call timeouts when the gateway is unreachable. + using CancellationTokenSource closeBudget = new(DisposeCloseTimeout); + await CloseAsync(closeBudget.Token).ConfigureAwait(false); } - catch (Exception ex) when (ex is MxGatewayException or ObjectDisposedException or RpcException) + catch (Exception ex) when (ex is MxGatewayException or ObjectDisposedException or RpcException or OperationCanceledException) { // Best-effort close: the gateway may be unreachable or the owning client // already disposed. Disposal must not throw or leak the lock; the gateway