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 diff --git a/clients/go/GoClientDesign.md b/clients/go/GoClientDesign.md index dd0d51b5..3ae236fd 100644 --- a/clients/go/GoClientDesign.md +++ b/clients/go/GoClientDesign.md @@ -54,6 +54,8 @@ type Options struct { ServerNameOverride string DialTimeout time.Duration CallTimeout time.Duration + KeepAliveTime time.Duration // default 30s; negative disables + KeepAliveTimeout time.Duration // default 10s } func Dial(ctx context.Context, opts Options) (*Client, error) @@ -94,6 +96,10 @@ authorization: Bearer ``` The interceptor should use `metadata.AppendToOutgoingContext` or call options. +Install it with `grpc.WithChainUnaryInterceptor` / `WithChainStreamInterceptor` so it +composes with caller interceptors, and have `Client` also attach the key per call so +`NewClient` over a caller-supplied connection authenticates. Dial sets HTTP/2 +keepalive (30 s ping, 10 s timeout, `PermitWithoutStream`) before `DialOptions`. Do not print API keys in errors. ## TLS @@ -132,8 +138,10 @@ type EventResult struct { } ``` -The receive goroutine exits on stream end, context cancellation, or error. The -channel should be closed exactly once. Do not reorder events. +The receive goroutine exits on stream end, context cancellation, or error, and +cancels the stream context on exit. Only a clean EOF or the caller's own +cancellation ends silently; a server-sent `Canceled` status or a deadline is a +terminal `Err`. The channel should be closed exactly once. Do not reorder events. ## Error Handling diff --git a/clients/go/README.md b/clients/go/README.md index c2ca0075..147bfd85 100644 --- a/clients/go/README.md +++ b/clients/go/README.md @@ -108,7 +108,32 @@ diagnostic that never decides the verdict. A nil entry is success. (the endpoint resolves with the `passthrough` scheme unless it names one) and then waits for the channel to become READY, bounded by `DialTimeout` (default 10 s) or the context deadline. A failure is returned as a `GatewayError` with -`Op == "dial"`. Passing a connection to `NewClient`/`NewGalaxyClient` stays lazy. +`Op == "dial"`. When the deadline expires the error still matches +`errors.Is(err, context.DeadlineExceeded)` and also carries the last connection +error (for example `connection refused` or a TLS verification failure). Passing a +connection to `NewClient`/`NewGalaxyClient` stays lazy. + +### Keepalive and authentication + +`Dial`/`DialGalaxy` enable HTTP/2 keepalive: a ping every `Options.KeepAliveTime` +(default `DefaultKeepAliveTime`, 30 s) with a `Options.KeepAliveTimeout` (default +`DefaultKeepAliveTimeout`, 10 s), sent even while no RPC is active +(`PermitWithoutStream`). Without it a stream `Recv` on a half-open connection +never returns. The gateway permits client pings at this rate by default; an +interval below the server's minimum draws a `too_many_pings` GOAWAY. A negative +`KeepAliveTime` disables it, and a `grpc.WithKeepaliveParams` in `DialOptions` +overrides it. Keepalive is a dial option, so a connection passed to `NewClient` +keeps whatever the caller configured. + +The API key is installed with the chain interceptor options, so a caller's own +`grpc.WithUnaryInterceptor` / `WithStreamInterceptor` in `DialOptions` composes +with it instead of replacing it. `Client`/`GalaxyClient` also attach +`Options.APIKey` to every call they make, so `NewClient(conn, Options{APIKey: k})` +over a shared connection authenticates; calls made directly on `RawClient()` rely on +the connection's own interceptor. + +`Register`, `AddItem` and `AddItem2` return a `*MalformedReplyError` for an OK reply +with neither the typed payload nor an int32 `return_value`, rather than handle 0. ### Event buffering @@ -406,8 +431,12 @@ for { ``` Cancel the supplied context to tear down the stream cleanly. Both channels -close after EOF, cancellation, or a terminal error; surfaced errors are wrapped -in `*GatewayError`. +close after EOF, cancellation, or a terminal error; `events` closes before `errs`, +so drain `events` and then read `errs`. A gateway-sent `Canceled` status or a context +deadline is delivered as a terminal error (only the caller's own cancellation ends +the stream silently); surfaced errors are wrapped in `*GatewayError`. The same rule +applies to `Session.Events`/`SubscribeEvents`: the stream context is also released +when the stream ends, so `EventsAfter` does not leak a context per reconnect. The CLI exposes the same RPC via `galaxy-watch`: @@ -500,6 +529,9 @@ sentinel, so a failing command does not abort the batch. The input scanner buffer is widened to 16 MiB so a single long command line (e.g. a bulk write with thousands of handles) does not trip bufio's default 64 KiB token-too-long limit; a line that still exceeds 16 MiB surfaces as a framed error and ends the session. +Consecutive lines with the same connection options reuse one dialed connection +(closed at EOF) instead of dialing per command. `bench-read-bulk` backs off +(10 ms doubling to 1 s) after consecutive failing calls instead of spinning. Use TLS options for a secured gateway. Over TLS (no `-plaintext`) with no `-ca-cert`, `mxgw-go` skips certificate verification by default (self-signed diff --git a/clients/go/cmd/mxgw-go/batchcache.go b/clients/go/cmd/mxgw-go/batchcache.go new file mode 100644 index 00000000..fc7d1524 --- /dev/null +++ b/clients/go/cmd/mxgw-go/batchcache.go @@ -0,0 +1,134 @@ +package main + +import ( + "context" + "sync" + "time" + + mxgateway "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/mxgateway" +) + +type batchCacheKey struct{} + +// batchConnection identifies one distinct connection configuration. +type batchConnection struct { + endpoint string + apiKey string + plaintext bool + caCertFile string + serverName string + requireTLS bool + timeout time.Duration +} + +func newBatchConnection(options commonOptions) batchConnection { + return batchConnection{ + endpoint: options.Endpoint, + apiKey: options.apiKeyValue, + plaintext: options.Plaintext, + caCertFile: options.CACertFile, + serverName: options.ServerName, + requireTLS: options.RequireCertificateValidation, + timeout: options.timeout, + } +} + +// batchClientCache keeps one dialed client per connection configuration for the +// lifetime of a batch run, so consecutive lines do not each pay a connection setup. +type batchClientCache struct { + mu sync.Mutex + clients map[batchConnection]*mxgateway.Client + galaxy map[batchConnection]*mxgateway.GalaxyClient +} + +func batchCacheFrom(ctx context.Context) *batchClientCache { + cache, _ := ctx.Value(batchCacheKey{}).(*batchClientCache) + return cache +} + +func (c *batchClientCache) client(ctx context.Context, options commonOptions) (*mxgateway.Client, error) { + key := newBatchConnection(options) + c.mu.Lock() + defer c.mu.Unlock() + if client, ok := c.clients[key]; ok { + return client, nil + } + client, err := mxgateway.Dial(ctx, options.dialOptions()) + if err != nil { + return nil, err + } + if c.clients == nil { + c.clients = map[batchConnection]*mxgateway.Client{} + } + c.clients[key] = client + return client, nil +} + +func (c *batchClientCache) galaxyClient(ctx context.Context, options commonOptions) (*mxgateway.GalaxyClient, error) { + key := newBatchConnection(options) + c.mu.Lock() + defer c.mu.Unlock() + if client, ok := c.galaxy[key]; ok { + return client, nil + } + client, err := mxgateway.DialGalaxy(ctx, options.dialOptions()) + if err != nil { + return nil, err + } + if c.galaxy == nil { + c.galaxy = map[batchConnection]*mxgateway.GalaxyClient{} + } + c.galaxy[key] = client + return client, nil +} + +func (c *batchClientCache) ownsClient(client *mxgateway.Client) bool { + c.mu.Lock() + defer c.mu.Unlock() + for _, cached := range c.clients { + if cached == client { + return true + } + } + return false +} + +func (c *batchClientCache) ownsGalaxyClient(client *mxgateway.GalaxyClient) bool { + c.mu.Lock() + defer c.mu.Unlock() + for _, cached := range c.galaxy { + if cached == client { + return true + } + } + return false +} + +func (c *batchClientCache) closeAll() { + c.mu.Lock() + defer c.mu.Unlock() + for _, client := range c.clients { + _ = client.Close() + } + for _, client := range c.galaxy { + _ = client.Close() + } + c.clients = nil + c.galaxy = nil +} + +// releaseClient closes a command's client unless the batch cache owns it. +func releaseClient(ctx context.Context, client *mxgateway.Client) { + if cache := batchCacheFrom(ctx); cache != nil && cache.ownsClient(client) { + return + } + _ = client.Close() +} + +// releaseGalaxyClient closes a command's Galaxy client unless the batch cache owns it. +func releaseGalaxyClient(ctx context.Context, client *mxgateway.GalaxyClient) { + if cache := batchCacheFrom(ctx); cache != nil && cache.ownsGalaxyClient(client) { + return + } + _ = client.Close() +} diff --git a/clients/go/cmd/mxgw-go/main.go b/clients/go/cmd/mxgw-go/main.go index d9dd6acf..26b13b8c 100644 --- a/clients/go/cmd/mxgw-go/main.go +++ b/clients/go/cmd/mxgw-go/main.go @@ -201,7 +201,7 @@ func runOpenSession(ctx context.Context, args []string, stdout, stderr io.Writer if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) reply, err := client.OpenSessionRaw(ctx, (&mxgateway.OpenSessionOptions{ RequestedBackend: *backend, @@ -241,7 +241,7 @@ func runCloseSession(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) reply, err := client.CloseSessionRaw(ctx, &mxgateway.CloseSessionRequest{SessionId: *sessionID}) if err != nil { @@ -278,7 +278,7 @@ func runPing(ctx context.Context, args []string, stdout, stderr io.Writer) error if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.PingRaw(ctx, *message) @@ -324,7 +324,7 @@ func runRegister(ctx context.Context, args []string, stdout, stderr io.Writer) e if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.RegisterRaw(ctx, *clientName) @@ -351,7 +351,7 @@ func runAddItem(ctx context.Context, args []string, stdout, stderr io.Writer) er if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.AddItemRaw(ctx, int32(*serverHandle), *item) @@ -378,7 +378,7 @@ func runAdvise(ctx context.Context, args []string, stdout, stderr io.Writer) err if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.AdviseRaw(ctx, int32(*serverHandle), int32(*itemHandle)) @@ -405,7 +405,7 @@ func runAdviseSupervisory(ctx context.Context, args []string, stdout, stderr io. if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.AdviseSupervisoryRaw(ctx, int32(*serverHandle), int32(*itemHandle)) @@ -441,7 +441,7 @@ func runWriteSecured(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.WriteSecuredRaw(ctx, int32(*serverHandle), int32(*itemHandle), int32(*currentUserID), int32(*verifierUserID), value) @@ -496,7 +496,7 @@ func runAuthenticateUser(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) // The raw reply carries only the resolved user id, never the credential, so @@ -526,7 +526,7 @@ func runSubscribeBulk(ctx context.Context, args []string, stdout, stderr io.Writ if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) results, err := session.SubscribeBulk(ctx, int32(*serverHandle), parseStringList(*items)) @@ -553,7 +553,7 @@ func runUnsubscribeBulk(ctx context.Context, args []string, stdout, stderr io.Wr if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) handles, err := parseInt32List(*itemHandles) if err != nil { @@ -586,7 +586,7 @@ func runReadBulk(ctx context.Context, args []string, stdout, stderr io.Writer) e if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) results, err := session.ReadBulk(ctx, int32(*serverHandle), parseStringList(*items), time.Duration(*timeoutMs)*time.Millisecond) @@ -682,7 +682,7 @@ func runWriteBulkVariant(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) @@ -777,7 +777,7 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session, err := client.OpenSession(ctx, mxgateway.OpenSessionOptions{ClientSessionName: *clientName}) if err != nil { @@ -814,15 +814,21 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ // failing ReadBulk calls until the wall-clock deadline elapses. warmupDeadline := time.Now().Add(time.Duration(*warmupSeconds) * time.Second) timeout := time.Duration(*timeoutMs) * time.Millisecond + warmupFailures := 0 for time.Now().Before(warmupDeadline) && ctx.Err() == nil { - _, _ = session.ReadBulk(ctx, serverHandle, tags, timeout) + if _, err := session.ReadBulk(ctx, serverHandle, tags, timeout); err != nil { + warmupFailures++ + benchBackoff(ctx, warmupFailures) + } else { + warmupFailures = 0 + } } // Steady state: per-call latency captured via time.Now() deltas. latenciesMs := make([]float64, 0, 65536) var totalReadResults int64 var cachedReadResults int64 - var successfulCalls, failedCalls int + var successfulCalls, failedCalls, consecutiveFailures int steadyStart := time.Now() steadyDeadline := steadyStart.Add(time.Duration(*durationSeconds) * time.Second) @@ -833,8 +839,11 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ latenciesMs = append(latenciesMs, float64(elapsed.Nanoseconds())/1e6) if err != nil { failedCalls++ + consecutiveFailures++ + benchBackoff(ctx, consecutiveFailures) continue } + consecutiveFailures = 0 successfulCalls++ for _, r := range results { totalReadResults++ @@ -876,6 +885,26 @@ func runBenchReadBulk(ctx context.Context, args []string, stdout, stderr io.Writ return nil } +// benchBackoff pauses after a failed ReadBulk. A failing call returns in microseconds, so +// without a pause the loop issues failing RPCs as fast as the CPU allows and burst-loads +// the gateway when it returns (CGO-008). The delay doubles from 10 ms to a 1 s cap. +func benchBackoff(ctx context.Context, consecutiveFailures int) { + shift := consecutiveFailures + if shift > 7 { + shift = 7 + } + delay := time.Duration(10< time.Second { + delay = time.Second + } + timer := time.NewTimer(delay) + defer timer.Stop() + select { + case <-timer.C: + case <-ctx.Done(): + } +} + // percentileSummary returns the same { p50, p95, p99, max, mean } shape every // language bench emits, rounded to 3 decimal places so the PowerShell driver // sees one schema across all five clients. @@ -955,7 +984,7 @@ func runWrite(ctx context.Context, args []string, stdout, stderr io.Writer) erro if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) reply, err := session.WriteRaw(ctx, int32(*serverHandle), int32(*itemHandle), value, int32(*userID)) @@ -982,7 +1011,7 @@ func runStreamEvents(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session := mxgateway.NewSessionForID(client, *sessionID) @@ -1060,7 +1089,7 @@ func runStreamAlarms(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) // Mirror runStreamEvents so Ctrl+C on a long-running stream-alarms command // cancels the gRPC stream cleanly (the gateway sees codes.Canceled rather @@ -1161,7 +1190,7 @@ func runAcknowledgeAlarm(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) reply, err := client.AcknowledgeAlarm(ctx, &mxgateway.AcknowledgeAlarmRequest{ AlarmFullReference: *reference, @@ -1204,7 +1233,7 @@ func runSmoke(ctx context.Context, args []string, stdout, stderr io.Writer) erro if err != nil { return err } - defer client.Close() + defer releaseClient(ctx, client) session, err := client.OpenSession(ctx, mxgateway.OpenSessionOptions{ClientSessionName: *clientName}) if err != nil { @@ -1309,15 +1338,12 @@ func dialForCommand(ctx context.Context, common *commonOptions) (*mxgateway.Clie return nil, options, err } - client, err := mxgateway.Dial(ctx, mxgateway.Options{ - Endpoint: options.Endpoint, - APIKey: options.apiKeyValue, - Plaintext: options.Plaintext, - CACertFile: options.CACertFile, - ServerNameOverride: options.ServerName, - RequireCertificateValidation: options.RequireCertificateValidation, - CallTimeout: options.timeout, - }) + if cache := batchCacheFrom(ctx); cache != nil { + client, err := cache.client(ctx, options) + return client, options, err + } + + client, err := mxgateway.Dial(ctx, options.dialOptions()) return client, options, err } @@ -1476,6 +1502,12 @@ const batchEOR = "__MXGW_BATCH_EOR__" // If a line still exceeds the cap, the error is surfaced as a per-command // error-with-sentinel and the session continues. func runBatch(ctx context.Context, in io.Reader, stdout, stderr io.Writer) error { + // One dialed client per distinct connection configuration, reused across lines instead + // of a blocking TCP/TLS/HTTP/2 dial per command (CGO-008). + cache := &batchClientCache{} + defer cache.closeAll() + ctx = context.WithValue(ctx, batchCacheKey{}, cache) + bw := bufio.NewWriter(stdout) scanner := bufio.NewScanner(in) scanner.Buffer(make([]byte, 0, 64*1024), 16*1024*1024) @@ -1526,18 +1558,27 @@ func dialGalaxyForCommand(ctx context.Context, common *commonOptions) (*mxgatewa return nil, options, err } - client, err := mxgateway.DialGalaxy(ctx, mxgateway.Options{ - Endpoint: options.Endpoint, - APIKey: options.apiKeyValue, - Plaintext: options.Plaintext, - CACertFile: options.CACertFile, - ServerNameOverride: options.ServerName, - RequireCertificateValidation: options.RequireCertificateValidation, - CallTimeout: options.timeout, - }) + if cache := batchCacheFrom(ctx); cache != nil { + client, err := cache.galaxyClient(ctx, options) + return client, options, err + } + + client, err := mxgateway.DialGalaxy(ctx, options.dialOptions()) return client, options, err } +func (o commonOptions) dialOptions() mxgateway.Options { + return mxgateway.Options{ + Endpoint: o.Endpoint, + APIKey: o.apiKeyValue, + Plaintext: o.Plaintext, + CACertFile: o.CACertFile, + ServerNameOverride: o.ServerName, + RequireCertificateValidation: o.RequireCertificateValidation, + CallTimeout: o.timeout, + } +} + func runGalaxyTestConnection(ctx context.Context, args []string, stdout, stderr io.Writer) error { flags := flag.NewFlagSet("galaxy-test-connection", flag.ContinueOnError) flags.SetOutput(stderr) @@ -1552,7 +1593,7 @@ func runGalaxyTestConnection(ctx context.Context, args []string, stdout, stderr if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) ok, err := client.TestConnection(ctx) if err != nil { @@ -1583,7 +1624,7 @@ func runGalaxyLastDeploy(ctx context.Context, args []string, stdout, stderr io.W if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) deployTime, present, err := client.GetLastDeployTime(ctx) if err != nil { @@ -1622,7 +1663,7 @@ func runGalaxyDiscover(ctx context.Context, args []string, stdout, stderr io.Wri if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) objects, err := client.DiscoverHierarchy(ctx) if err != nil { @@ -1670,7 +1711,7 @@ func runGalaxyWatch(ctx context.Context, args []string, stdout, stderr io.Writer if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) signalCtx, stopSignals := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) defer stopSignals() @@ -1683,22 +1724,28 @@ func runGalaxyWatch(ctx context.Context, args []string, stdout, stderr io.Writer return err } + printEvent := func(event *mxgateway.DeployEvent) { + if *jsonOutput { + fmt.Fprintln(stdout, string(mustMarshalProto(event))) + } else { + fmt.Fprintln(stdout, formatDeployEvent(event)) + } + } + count := 0 + selectErrs := errs for { select { case event, ok := <-events: if !ok { - // Drain any terminal error before returning. + // events closes before errs, so the terminal error (if any) is already buffered or + // about to be: drain it before returning. if streamErr, errOk := <-errs; errOk && streamErr != nil { return streamErr } return nil } - if *jsonOutput { - fmt.Fprintln(stdout, string(mustMarshalProto(event))) - } else { - fmt.Fprintln(stdout, formatDeployEvent(event)) - } + printEvent(event) count++ if *limit > 0 && count >= *limit { cancelStream() @@ -1710,13 +1757,23 @@ func runGalaxyWatch(ctx context.Context, args []string, stdout, stderr io.Writer } return nil } - case streamErr, ok := <-errs: + case streamErr, ok := <-selectErrs: if !ok { - return nil + // A closed errs channel is not the end of the stream: events may still hold + // buffered items. Stop selecting on it and let the events branch finish + // the drain (CGO-006). + selectErrs = nil + continue + } + // The terminal error is sent after every event was queued: print what is still + // buffered before reporting it so the last events are not lost. + for event := range events { + printEvent(event) } if streamErr != nil { return streamErr } + return nil case <-signalCtx.Done(): cancelStream() // Allow goroutine to drain. @@ -1782,7 +1839,7 @@ func runGalaxyBrowse(ctx context.Context, args []string, stdout, stderr io.Write if err != nil { return err } - defer client.Close() + defer releaseGalaxyClient(ctx, client) // A specific parent → one level of children via the raw parent-scoped RPC. if *parent >= 0 { diff --git a/clients/go/cmd/mxgw-go/main_test.go b/clients/go/cmd/mxgw-go/main_test.go index 05ed4358..a8ae0193 100644 --- a/clients/go/cmd/mxgw-go/main_test.go +++ b/clients/go/cmd/mxgw-go/main_test.go @@ -7,11 +7,14 @@ import ( "flag" "net" "strings" + "sync/atomic" "testing" "time" pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) func TestRunVersionJSON(t *testing.T) { @@ -881,3 +884,119 @@ func TestRequireCertificateValidationFlag(t *testing.T) { t.Fatal("flag must set RequireCertificateValidation") } } + +// countingListener counts accepted connections so a test can assert connection reuse. +type countingListener struct { + net.Listener + accepts atomic.Int32 +} + +func (l *countingListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err == nil { + l.accepts.Add(1) + } + return conn, err +} + +// TestRunBatchReusesOneConnectionAcrossLines pins CGO-008: batch mode dials once per +// connection configuration rather than once per line. +func TestRunBatchReusesOneConnectionAcrossLines(t *testing.T) { + raw, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + listener := &countingListener{Listener: raw} + server := grpc.NewServer() + pb.RegisterMxAccessGatewayServer(server, &benchFakeGateway{}) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + + line := "close-session -endpoint " + raw.Addr().String() + " -plaintext -api-key k -session-id s -json\n" + var stdout, stderr bytes.Buffer + if err := runBatch(t.Context(), strings.NewReader(line+line+line), &stdout, &stderr); err != nil { + t.Fatalf("runBatch() error = %v; stderr = %s", err, stderr.String()) + } + if got := strings.Count(stdout.String(), batchEOR); got != 3 { + t.Fatalf("EOR count = %d, want 3; out = %s", got, stdout.String()) + } + if got := listener.accepts.Load(); got != 1 { + t.Fatalf("server accepted %d connections for 3 batch lines, want 1", got) + } +} + +type failingReadBulkGateway struct { + benchFakeGateway + readBulkCalls atomic.Int32 +} + +func (g *failingReadBulkGateway) Invoke(ctx context.Context, req *pb.MxCommandRequest) (*pb.MxCommandReply, error) { + if req.GetCommand().GetKind() == pb.MxCommandKind_MX_COMMAND_KIND_READ_BULK { + g.readBulkCalls.Add(1) + return nil, status.Error(codes.Unavailable, "gateway down") + } + return g.benchFakeGateway.Invoke(ctx, req) +} + +// TestRunBenchReadBulkBacksOffOnFailures pins CGO-008: failing ReadBulk calls must not +// spin as fast as the CPU allows. +func TestRunBenchReadBulkBacksOffOnFailures(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + fake := &failingReadBulkGateway{} + server := grpc.NewServer() + pb.RegisterMxAccessGatewayServer(server, fake) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + + var stdout, stderr bytes.Buffer + args := []string{ + "bench-read-bulk", "-endpoint", listener.Addr().String(), "-plaintext", "-api-key", "k", + "-duration-seconds", "1", "-warmup-seconds", "0", "-bulk-size", "1", "-json", + } + if err := runWithIO(t.Context(), args, &stdout, &stderr); err != nil { + t.Fatalf("runWithIO() error = %v; stderr = %s", err, stderr.String()) + } + if calls := fake.readBulkCalls.Load(); calls > 40 { + t.Fatalf("%d failing ReadBulk calls in a 1 s window, want a bounded number (backoff)", calls) + } +} + +type watchFakeGalaxy struct { + pb.UnimplementedGalaxyRepositoryServer +} + +func (g *watchFakeGalaxy) WatchDeployEvents(_ *pb.WatchDeployEventsRequest, stream grpc.ServerStreamingServer[pb.DeployEvent]) error { + for i := 0; i < 3; i++ { + if err := stream.Send(&pb.DeployEvent{}); err != nil { + return err + } + } + return nil +} + +// TestRunGalaxyWatchPrintsEveryBufferedEventBeforeExit pins CGO-006: the CLI must not return +// on a closed error channel while events are still buffered. +func TestRunGalaxyWatchPrintsEveryBufferedEventBeforeExit(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + server := grpc.NewServer() + pb.RegisterGalaxyRepositoryServer(server, &watchFakeGalaxy{}) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + + for i := 0; i < 20; i++ { + var stdout, stderr bytes.Buffer + args := []string{"galaxy-watch", "-endpoint", listener.Addr().String(), "-plaintext", "-api-key", "k", "-json"} + if err := runWithIO(t.Context(), args, &stdout, &stderr); err != nil { + t.Fatalf("runWithIO() error = %v; stderr = %s", err, stderr.String()) + } + if got := len(strings.Split(strings.TrimSpace(stdout.String()), "\n")); got != 3 { + t.Fatalf("iteration %d printed %d events, want 3; out = %q", i, got, stdout.String()) + } + } +} diff --git a/clients/go/mxgateway/alarms.go b/clients/go/mxgateway/alarms.go index b0fe2abf..25b1a56a 100644 --- a/clients/go/mxgateway/alarms.go +++ b/clients/go/mxgateway/alarms.go @@ -49,7 +49,7 @@ func (c *Client) QueryActiveAlarms(ctx context.Context, req *QueryActiveAlarmsRe return nil, errors.New("mxgateway: query active alarms request is required") } - stream, err := c.raw.QueryActiveAlarms(ctx, req) + stream, err := c.raw.QueryActiveAlarms(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "query active alarms", Err: err} } @@ -72,7 +72,7 @@ func (c *Client) StreamAlarms(ctx context.Context, req *StreamAlarmsRequest) (St return nil, errors.New("mxgateway: stream alarms request is required") } - stream, err := c.raw.StreamAlarms(ctx, req) + stream, err := c.raw.StreamAlarms(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "stream alarms", Err: err} } diff --git a/clients/go/mxgateway/auth.go b/clients/go/mxgateway/auth.go index b8157b9d..164c74d4 100644 --- a/clients/go/mxgateway/auth.go +++ b/clients/go/mxgateway/auth.go @@ -25,6 +25,11 @@ func authContext(ctx context.Context, apiKey string) context.Context { if apiKey == "" { return ctx } + // Idempotent: the client attaches the key per call and the dial interceptor + // may attach it again, which must not send two authorization headers. + if md, ok := metadata.FromOutgoingContext(ctx); ok && len(md.Get(authorizationHeader)) > 0 { + return ctx + } return metadata.AppendToOutgoingContext(ctx, authorizationHeader, "Bearer "+apiKey) } diff --git a/clients/go/mxgateway/client.go b/clients/go/mxgateway/client.go index 5b647cf6..c837fabb 100644 --- a/clients/go/mxgateway/client.go +++ b/clients/go/mxgateway/client.go @@ -15,6 +15,7 @@ import ( "context" "crypto/tls" "errors" + "fmt" "strings" "time" @@ -23,7 +24,9 @@ import ( "google.golang.org/grpc/connectivity" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/emptypb" ) const ( @@ -59,14 +62,7 @@ func Dial(ctx context.Context, opts Options) (*Client, error) { return nil, err } - dialOptions := []grpc.DialOption{ - grpc.WithTransportCredentials(transportCredentials), - grpc.WithUnaryInterceptor(unaryAuthInterceptor(opts.APIKey)), - grpc.WithStreamInterceptor(streamAuthInterceptor(opts.APIKey)), - } - dialOptions = append(dialOptions, opts.DialOptions...) - - conn, err := dialConnected(dialCtx, opts.Endpoint, dialOptions) + conn, err := dialConnected(dialCtx, opts.Endpoint, buildDialOptions(opts, transportCredentials)) if err != nil { return nil, &GatewayError{Op: "dial", Err: err} } @@ -74,6 +70,23 @@ func Dial(ctx context.Context, opts Options) (*Client, error) { return NewClient(conn, opts), nil } +// buildDialOptions assembles the dial options shared by Dial and DialGalaxy. The +// defaults (keepalive, auth) come before opts.DialOptions so callers can override +// keepalive. Auth is installed with the chain interceptor options, which compose +// with — rather than replace — a caller's own WithUnaryInterceptor / +// WithStreamInterceptor (CGO-002). +func buildDialOptions(opts Options, transportCredentials credentials.TransportCredentials) []grpc.DialOption { + dialOptions := []grpc.DialOption{ + grpc.WithTransportCredentials(transportCredentials), + grpc.WithChainUnaryInterceptor(unaryAuthInterceptor(opts.APIKey)), + grpc.WithChainStreamInterceptor(streamAuthInterceptor(opts.APIKey)), + } + if params, ok := opts.keepAliveParams(); ok { + dialOptions = append(dialOptions, grpc.WithKeepaliveParams(params)) + } + return append(dialOptions, opts.DialOptions...) +} + // NewClient wraps an existing gRPC connection. The caller owns closing conn // unless it calls Close on the returned Client. func NewClient(conn *grpc.ClientConn, opts Options) *Client { @@ -171,7 +184,7 @@ func (c *Client) StreamEventsRaw(ctx context.Context, req *StreamEventsRequest) return nil, errors.New("mxgateway: stream events request is required") } - stream, err := c.raw.StreamEvents(ctx, req) + stream, err := c.raw.StreamEvents(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "stream events", Err: err} } @@ -193,6 +206,10 @@ func (c *Client) callContext(ctx context.Context) (context.Context, context.Canc if timeout == 0 { timeout = defaultCallTimeout } + // The API key is attached here as well as by the dial-time interceptors, so a + // client built with NewClient over a caller-supplied connection (no auth + // interceptor) still authenticates. authContext is idempotent. + ctx = authContext(ctx, c.opts.APIKey) if timeout < 0 { return ctx, func() {} } @@ -282,6 +299,7 @@ func dialConnected(ctx context.Context, endpoint string, dialOptions []grpc.Dial return nil, err } conn.Connect() + var lastCause error for { state := conn.GetState() if state == connectivity.Ready { @@ -291,9 +309,37 @@ func dialConnected(ctx context.Context, endpoint string, dialOptions []grpc.Dial _ = conn.Close() return nil, errors.New("connection shut down while connecting") } + if state == connectivity.TransientFailure { + // Keep waiting (the gateway may be restarting) but remember why the last attempt + // failed: ctx.Err() alone reports only "deadline exceeded" for a refused + // connection or a TLS verification failure (CGO-005). + if cause := connectionFailureCause(ctx, conn); cause != nil { + lastCause = cause + } + } if !conn.WaitForStateChange(ctx, state) { _ = conn.Close() + if lastCause != nil { + return nil, fmt.Errorf("%w: last connection error: %v", ctx.Err(), lastCause) + } return nil, ctx.Err() } } } + +// connectionFailureCause issues a fail-fast RPC on a channel in TRANSIENT_FAILURE. +// grpc-go does not expose the dial error directly, but a non-wait-for-ready RPC +// fails immediately with Unavailable carrying "connection error: desc = ...". The +// RPC never reaches a server, so the method name is arbitrary. +func connectionFailureCause(ctx context.Context, conn *grpc.ClientConn) error { + probeCtx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + err := conn.Invoke(probeCtx, "/mxaccess_gateway.v1.MxAccessGateway/ConnectionProbe", &emptypb.Empty{}, &emptypb.Empty{}) + if err == nil { + return nil + } + if st, ok := status.FromError(err); ok { + return errors.New(st.Message()) + } + return err +} diff --git a/clients/go/mxgateway/galaxy.go b/clients/go/mxgateway/galaxy.go index 8d09056a..e900f5de 100644 --- a/clients/go/mxgateway/galaxy.go +++ b/clients/go/mxgateway/galaxy.go @@ -10,8 +10,6 @@ import ( pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -95,14 +93,7 @@ func DialGalaxy(ctx context.Context, opts Options) (*GalaxyClient, error) { return nil, err } - dialOptions := []grpc.DialOption{ - grpc.WithTransportCredentials(transportCredentials), - grpc.WithUnaryInterceptor(unaryAuthInterceptor(opts.APIKey)), - grpc.WithStreamInterceptor(streamAuthInterceptor(opts.APIKey)), - } - dialOptions = append(dialOptions, opts.DialOptions...) - - conn, err := dialConnected(dialCtx, opts.Endpoint, dialOptions) + conn, err := dialConnected(dialCtx, opts.Endpoint, buildDialOptions(opts, transportCredentials)) if err != nil { return nil, &GatewayError{Op: "dial", Err: err} } @@ -203,7 +194,7 @@ func (c *GalaxyClient) WatchDeployEventsRaw(ctx context.Context, req *WatchDeplo req = &pb.WatchDeployEventsRequest{} } - stream, err := c.raw.WatchDeployEvents(ctx, req) + stream, err := c.raw.WatchDeployEvents(authContext(ctx, c.opts.APIKey), req) if err != nil { return nil, &GatewayError{Op: "galaxy watch deploy events", Err: err} } @@ -238,8 +229,10 @@ func (c *GalaxyClient) WatchDeployEvents( events := make(chan *DeployEvent, 16) errs := make(chan error, 1) go func() { - defer close(events) + // events closes before errs (defers run last-in first-out) so a consumer that + // selects on both never sees errs close while events are still buffered (CGO-006). defer close(errs) + defer close(events) for { event, recvErr := stream.Recv() if recvErr == nil { @@ -253,12 +246,16 @@ func (c *GalaxyClient) WatchDeployEvents( if recvErr == io.EOF { return } - if status.Code(recvErr) == codes.Canceled || ctx.Err() != nil { + // Silent end only for the caller's own cancellation; a gateway-sent Canceled + // status or a context deadline is reported as a terminal error (CGO-003). + if errors.Is(ctx.Err(), context.Canceled) { return } + // errs has room for one error; a plain select against ctx.Done() could drop it + // at random when ctx has expired. select { case errs <- &GatewayError{Op: "galaxy watch deploy events", Err: recvErr}: - case <-ctx.Done(): + default: } return } @@ -480,6 +477,10 @@ func (c *GalaxyClient) callContext(ctx context.Context) (context.Context, contex if timeout == 0 { timeout = defaultCallTimeout } + // The API key is attached here as well as by the dial-time interceptors, so a + // client built with NewClient over a caller-supplied connection (no auth + // interceptor) still authenticates. authContext is idempotent. + ctx = authContext(ctx, c.opts.APIKey) if timeout < 0 { return ctx, func() {} } diff --git a/clients/go/mxgateway/galaxy_test.go b/clients/go/mxgateway/galaxy_test.go index ffa165db..c8ad98df 100644 --- a/clients/go/mxgateway/galaxy_test.go +++ b/clients/go/mxgateway/galaxy_test.go @@ -425,6 +425,7 @@ type fakeGalaxyServer struct { watchRequest *pb.WatchDeployEventsRequest watchSendInterval time.Duration watchHoldOpen bool + watchTerminalErr error browseChildrenCalls []*pb.BrowseChildrenRequest browseChildrenReplies []*pb.BrowseChildrenReply browseChildrenError error @@ -475,6 +476,9 @@ func (s *fakeGalaxyServer) WatchDeployEvents(req *pb.WatchDeployEventsRequest, s } } } + if s.watchTerminalErr != nil { + return s.watchTerminalErr + } if s.watchHoldOpen { <-stream.Context().Done() } diff --git a/clients/go/mxgateway/options.go b/clients/go/mxgateway/options.go index 173e406d..99f9ff27 100644 --- a/clients/go/mxgateway/options.go +++ b/clients/go/mxgateway/options.go @@ -7,6 +7,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/keepalive" ) // Options configures gateway connections. @@ -26,6 +27,17 @@ type Options struct { // CallTimeout bounds each unary RPC; zero applies a built-in default and // negative disables the bound entirely. CallTimeout time.Duration + // KeepAliveTime is the interval between HTTP/2 keepalive pings. Zero applies + // DefaultKeepAliveTime (30 s); negative disables client keepalive. Pings are + // sent even while no RPC is active so a half-open connection under an idle + // event stream is detected. The gateway permits client pings at this rate by + // default; an interval shorter than the server's minimum draws a GOAWAY + // "too_many_pings". + KeepAliveTime time.Duration + // KeepAliveTimeout is how long to wait for a ping acknowledgement before the + // connection is closed and in-flight RPCs fail. Zero applies + // DefaultKeepAliveTimeout (10 s). + KeepAliveTimeout time.Duration // TLSConfig supplies a custom TLS configuration; takes precedence over // CACertFile when TransportCredentials is unset. TLSConfig *tls.Config @@ -45,6 +57,34 @@ type Options struct { EventBufferSize int } +// Default HTTP/2 keepalive values (D7), identical across the five gateway clients. +const ( + // DefaultKeepAliveTime is the default Options.KeepAliveTime. + DefaultKeepAliveTime = 30 * time.Second + // DefaultKeepAliveTimeout is the default Options.KeepAliveTimeout. + DefaultKeepAliveTimeout = 10 * time.Second +) + +// keepAliveParams returns the keepalive parameters for the options, and false when +// keepalive is disabled. PermitWithoutStream keeps pinging while no call is active. +func (o Options) keepAliveParams() (keepalive.ClientParameters, bool) { + if o.KeepAliveTime < 0 { + return keepalive.ClientParameters{}, false + } + params := keepalive.ClientParameters{ + Time: o.KeepAliveTime, + Timeout: o.KeepAliveTimeout, + PermitWithoutStream: true, + } + if params.Time == 0 { + params.Time = DefaultKeepAliveTime + } + if params.Timeout == 0 { + params.Timeout = DefaultKeepAliveTimeout + } + return params, true +} + // DefaultEventBufferSize is the default Options.EventBufferSize. const DefaultEventBufferSize = 1024 diff --git a/clients/go/mxgateway/review_phase6_test.go b/clients/go/mxgateway/review_phase6_test.go new file mode 100644 index 00000000..afd73daf --- /dev/null +++ b/clients/go/mxgateway/review_phase6_test.go @@ -0,0 +1,302 @@ +package mxgateway + +import ( + "context" + "errors" + "io" + "net" + "strings" + "testing" + "time" + + pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" +) + +func TestKeepAliveDefaultsMatchDecisionD7(t *testing.T) { + params, ok := (Options{}).keepAliveParams() + if !ok { + t.Fatal("keepalive disabled by default, want enabled") + } + if params.Time != 30*time.Second || params.Timeout != 10*time.Second { + t.Fatalf("keepalive = %v / %v, want 30s / 10s", params.Time, params.Timeout) + } + if !params.PermitWithoutStream { + t.Fatal("PermitWithoutStream = false, want pings while no call is active") + } +} + +func TestKeepAliveConfigurable(t *testing.T) { + params, ok := (Options{KeepAliveTime: 45 * time.Second, KeepAliveTimeout: 5 * time.Second}).keepAliveParams() + if !ok || params.Time != 45*time.Second || params.Timeout != 5*time.Second { + t.Fatalf("keepalive = %+v ok=%v, want 45s / 5s", params, ok) + } + if _, ok := (Options{KeepAliveTime: -1}).keepAliveParams(); ok { + t.Fatal("negative KeepAliveTime should disable keepalive") + } +} + +// A caller-supplied single interceptor must compose with the auth interceptor instead of +// replacing it (CGO-002). +func TestDialAuthComposesWithCallerInterceptors(t *testing.T) { + fake := &fakeGatewayServer{} + callerSawCall := false + client, cleanup := newBufconnClientWithOptions(t, fake, Options{ + DialOptions: []grpc.DialOption{ + grpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { + callerSawCall = true + return invoker(ctx, method, req, reply, cc, opts...) + }), + }, + }) + defer cleanup() + + if _, err := client.OpenSession(context.Background(), OpenSessionOptions{}); err != nil { + t.Fatalf("OpenSession() error = %v", err) + } + if !callerSawCall { + t.Fatal("caller interceptor did not run") + } + if fake.openAuth != "Bearer test-api-key" { + t.Fatalf("authorization = %q, want the API key", fake.openAuth) + } +} + +// NewClient over a caller-supplied connection has no dial-time interceptor; the client +// itself must attach Options.APIKey (CGO-002). +func TestNewClientAttachesAPIKeyWithoutDialInterceptor(t *testing.T) { + fake := &fakeGatewayServer{} + listener := bufconn.Listen(bufSize) + server := grpc.NewServer() + pb.RegisterMxAccessGatewayServer(server, fake) + go func() { _ = server.Serve(listener) }() + defer server.Stop() + conn, err := grpc.NewClient("passthrough:///bufnet", + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) })) + if err != nil { + t.Fatalf("NewClient conn: %v", err) + } + defer conn.Close() + + client := NewClient(conn, Options{APIKey: "shared-conn-key"}) + if _, err := client.OpenSession(context.Background(), OpenSessionOptions{}); err != nil { + t.Fatalf("OpenSession() error = %v", err) + } + if fake.openAuth != "Bearer shared-conn-key" { + t.Fatalf("authorization = %q, want the API key from Options", fake.openAuth) + } + // Dial-installed interceptor + per-call attach must not double the header. + fake2 := &fakeGatewayServer{} + client2, cleanup := newBufconnClient(t, fake2) + defer cleanup() + if _, err := client2.OpenSession(context.Background(), OpenSessionOptions{}); err != nil { + t.Fatalf("OpenSession() error = %v", err) + } + if fake2.openAuth != "Bearer test-api-key" { + t.Fatalf("authorization = %q", fake2.openAuth) + } +} + +// A Canceled status the gateway sends while the caller's context is live is not a clean end +// (CGO-003): the consumer must see a terminal error. +func TestEventsServerCanceledStatusIsTerminalError(t *testing.T) { + fake := &fakeGatewayServer{streamTerminalErr: status.Error(codes.Canceled, "gateway shutting down")} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + session := NewSessionForID(client, "session-1") + + events, err := session.Events(context.Background()) + if err != nil { + t.Fatalf("Events() error = %v", err) + } + var sawErr error + for result := range events { + if result.Err != nil { + sawErr = result.Err + } + } + if sawErr == nil { + t.Fatal("stream ended with no terminal error, want the Canceled status surfaced") + } + if status.Code(errors.Unwrap(sawErr)) != codes.Canceled { + t.Fatalf("terminal error = %v, want the Canceled gRPC status preserved", sawErr) + } +} + +// A context deadline that ends the stream is reported, not silent (CGO-003). +func TestEventsContextDeadlineIsTerminalError(t *testing.T) { + fake := &fakeGatewayServer{} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + session := NewSessionForID(client, "session-1") + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + + events, err := session.SubscribeEvents(ctx) + if err != nil { + t.Fatalf("SubscribeEvents() error = %v", err) + } + var sawErr error + for result := range events.Events() { + if result.Err != nil { + sawErr = result.Err + } + } + if sawErr == nil { + t.Fatal("deadline ended the stream silently, want a terminal error") + } + if status.Code(errors.Unwrap(sawErr)) != codes.DeadlineExceeded { + t.Fatalf("terminal error = %v, want DeadlineExceeded", sawErr) + } +} + +// The caller's own cancellation still ends the stream with no error. +func TestEventsCallerCancelEndsSilently(t *testing.T) { + fake := &fakeGatewayServer{streamStarted: make(chan struct{})} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + session := NewSessionForID(client, "session-1") + ctx, cancel := context.WithCancel(context.Background()) + + events, err := session.Events(ctx) + if err != nil { + t.Fatalf("Events() error = %v", err) + } + <-fake.streamStarted + cancel() + for result := range events { + if result.Err != nil { + t.Fatalf("caller cancellation surfaced error %v, want a silent close", result.Err) + } + } +} + +type ctxCapturingRaw struct { + pb.MxAccessGatewayClient + streamCtx context.Context +} + +func (f *ctxCapturingRaw) StreamEvents(ctx context.Context, _ *pb.StreamEventsRequest, _ ...grpc.CallOption) (grpc.ServerStreamingClient[pb.MxEvent], error) { + f.streamCtx = ctx + return eofEventStream{}, nil +} + +type eofEventStream struct{ grpc.ClientStream } + +func (eofEventStream) Recv() (*pb.MxEvent, error) { return nil, io.EOF } + +// The stream context is released when the stream ends, not only on Close (CGO-004). +func TestEventsCancelsStreamContextOnEOF(t *testing.T) { + raw := &ctxCapturingRaw{} + client := &Client{raw: raw} + session := NewSessionForID(client, "session-1") + parent, cancel := context.WithCancel(context.Background()) + defer cancel() + + events, err := session.EventsAfter(parent, 0) + if err != nil { + t.Fatalf("EventsAfter() error = %v", err) + } + for range events { + } + deadline := time.After(2 * time.Second) + for raw.streamCtx.Err() == nil { + select { + case <-deadline: + t.Fatal("stream context still live after EOF; the per-stream cancelCtx leaks") + case <-time.After(5 * time.Millisecond): + } + } +} + +func TestDialErrorIncludesLastConnectionCause(t *testing.T) { + start := time.Now() + _, err := Dial(context.Background(), Options{ + Endpoint: "bufnet", + Plaintext: true, + DialTimeout: 1500 * time.Millisecond, + DialOptions: []grpc.DialOption{grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { + return nil, errors.New("connection refused by test dialer") + })}, + }) + if err == nil { + t.Fatal("Dial() error = nil") + } + if !strings.Contains(err.Error(), "connection refused by test dialer") { + t.Fatalf("Dial() error = %q, want it to carry the underlying connection error", err) + } + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("Dial() error = %v, want errors.Is(DeadlineExceeded) preserved", err) + } + if time.Since(start) > 5*time.Second { + t.Fatalf("Dial() took %v", time.Since(start)) + } +} + +func TestHandleReturningCommandsRejectMissingPayload(t *testing.T) { + for _, tc := range []struct { + name string + call func(*Session) error + }{ + {"register", func(s *Session) error { _, err := s.Register(context.Background(), "c"); return err }}, + {"add item", func(s *Session) error { _, err := s.AddItem(context.Background(), 1, "Tag.A"); return err }}, + {"add item2", func(s *Session) error { _, err := s.AddItem2(context.Background(), 1, "Tag.A", "ctx"); return err }}, + } { + t.Run(tc.name, func(t *testing.T) { + fake := &fakeGatewayServer{invokeReply: &pb.MxCommandReply{SessionId: "session-1", ProtocolStatus: okStatus()}} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + err := tc.call(NewSessionForID(client, "session-1")) + var malformed *MalformedReplyError + if !errors.As(err, &malformed) { + t.Fatalf("error = %v, want *MalformedReplyError", err) + } + }) + } +} + +func TestRegisterAcceptsInt32ReturnValueWithoutPayload(t *testing.T) { + fake := &fakeGatewayServer{invokeReply: &pb.MxCommandReply{ + SessionId: "session-1", + ProtocolStatus: okStatus(), + ReturnValue: &pb.MxValue{Kind: &pb.MxValue_Int32Value{Int32Value: 7}}, + }} + client, cleanup := newBufconnClient(t, fake) + defer cleanup() + handle, err := NewSessionForID(client, "session-1").Register(context.Background(), "c") + if err != nil || handle != 7 { + t.Fatalf("Register() = %d, %v; want 7, nil", handle, err) + } +} + +// A Canceled status from the gateway while the caller's context is live is reported on the +// error channel, and events queued before it are still delivered (CGO-003, CGO-006). +func TestWatchDeployEventsServerCanceledIsReportedAfterEvents(t *testing.T) { + fake := &fakeGalaxyServer{ + watchEvents: []*pb.DeployEvent{{}, {}, {}}, + watchTerminalErr: status.Error(codes.Canceled, "gateway shutting down"), + } + client, cleanup := newGalaxyBufconnClient(t, fake) + defer cleanup() + + events, errs, err := client.WatchDeployEvents(context.Background(), nil) + if err != nil { + t.Fatalf("WatchDeployEvents() error = %v", err) + } + received := 0 + for range events { + received++ + } + if received != 3 { + t.Fatalf("received %d events, want 3", received) + } + streamErr, ok := <-errs + if !ok || streamErr == nil { + t.Fatal("no terminal error for a gateway-sent Canceled status") + } +} diff --git a/clients/go/mxgateway/session.go b/clients/go/mxgateway/session.go index b2a0223c..eb8e21e8 100644 --- a/clients/go/mxgateway/session.go +++ b/clients/go/mxgateway/session.go @@ -13,8 +13,6 @@ import ( "time" pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" ) const maxBulkItems = 1000 @@ -143,7 +141,13 @@ func (s *Session) Register(ctx context.Context, clientName string) (int32, error if reply.GetRegister() != nil { return reply.GetRegister().GetServerHandle(), nil } - return reply.GetReturnValue().GetInt32Value(), nil + if x, ok := reply.GetReturnValue().GetKind().(*pb.MxValue_Int32Value); ok { + return x.Int32Value, nil + } + return 0, &MalformedReplyError{ + Op: "register", + Detail: "reply carried neither a Register payload nor an int32 return_value", + } } // RegisterRaw invokes MXAccess Register and returns the raw reply. @@ -199,7 +203,13 @@ func (s *Session) AddItem(ctx context.Context, serverHandle int32, itemDefinitio if reply.GetAddItem() != nil { return reply.GetAddItem().GetItemHandle(), nil } - return reply.GetReturnValue().GetInt32Value(), nil + if x, ok := reply.GetReturnValue().GetKind().(*pb.MxValue_Int32Value); ok { + return x.Int32Value, nil + } + return 0, &MalformedReplyError{ + Op: "add item", + Detail: "reply carried neither a AddItem payload nor an int32 return_value", + } } // AddItemRaw invokes MXAccess AddItem and returns the raw reply. @@ -228,7 +238,13 @@ func (s *Session) AddItem2(ctx context.Context, serverHandle int32, itemDefiniti if reply.GetAddItem2() != nil { return reply.GetAddItem2().GetItemHandle(), nil } - return reply.GetReturnValue().GetInt32Value(), nil + if x, ok := reply.GetReturnValue().GetKind().(*pb.MxValue_Int32Value); ok { + return x.Int32Value, nil + } + return 0, &MalformedReplyError{ + Op: "add item2", + Detail: "reply carried neither a AddItem2 payload nor an int32 return_value", + } } // AddItem2Raw invokes MXAccess AddItem2 and returns the raw reply. @@ -1118,6 +1134,10 @@ func (s *Session) subscribeEventsAfter(ctx context.Context, afterWorkerSequence results := make(chan EventResult, dataSlots+eventBufferReservedSlots) done := make(chan struct{}) go func() { + // Release the stream context when the stream ends (EOF or terminal error), not only + // on EventSubscription.Close: Events/EventsAfter hand the caller no handle, so + // without this each reconnect leaves a child context attached to ctx (CGO-004). + defer cancel() defer close(results) defer close(done) for { @@ -1136,7 +1156,12 @@ func (s *Session) subscribeEventsAfter(ctx context.Context, afterWorkerSequence } continue } - if err == io.EOF || status.Code(err) == codes.Canceled || streamCtx.Err() != nil { + // Silent end only for a clean server end or the caller's own cancellation. A + // Canceled status while the context is still live was produced by the gateway + // (session closed/killed, shutdown), and a context deadline is not a clean end + // either: both are delivered as a terminal error so the consumer can tell them + // from the session simply closing (CGO-003). + if err == io.EOF || errors.Is(streamCtx.Err(), context.Canceled) { return } // A genuine terminal stream error must be reported as itself, even @@ -1178,11 +1203,14 @@ func ensureBulkSize(name string, length int) error { // silently drop the terminal error, breaking the never-drop contract; instead // block until the consumer drains a slot (or the stream context is cancelled). func sendTerminalEventResult(ctx context.Context, results chan<- EventResult, result EventResult, cancelWhenBufferFull bool) { + // Prefer a free slot: when ctx is already done (a deadline ended the stream), a plain + // select between the send and ctx.Done() could randomly drop the terminal error. + select { + case results <- result: + return + default: + } if cancelWhenBufferFull { - select { - case results <- result: - default: - } return } select {