fix(client-dotnet): keepalive, error mapping, lifecycle, CLI batch/redaction (CDN-001..011, #257)

- keepalive: 30 s ping / 10 s timeout / Always, configurable via KeepAlivePingDelay/Timeout (CDN-004, D7)
- GrpcStatusMapper shared by both transports: server Cancelled with a live token is no longer
  OperationCanceledException; NotFound/FailedPrecondition on session RPCs -> MxGatewaySessionException;
  MxGatewayException.GrpcStatusCode preserves the status (CDN-001, CDN-002)
- Register/AddItem/AddItem2 raise MxGatewayMalformedReplyException on a payload-less reply (CDN-008)
- MxGatewayEventStream.DisposeAsync waits for the in-flight read (CDN-003); session DisposeAsync
  is bounded to 5 s and swallows cancellation (CDN-005); owned handler + pinned CA disposed (CDN-006)
- ResourceExhausted no longer retried (CDN-007)
- CLI: batch reuses clients, stream/bench commands exempt from the 30 s timeout, OCE reported as
  an error with exit 1, --value redacted only for write-secured* and only as a whole token,
  bench backs off on failures (CDN-009, CDN-010, CDN-011)
This commit is contained in:
Joseph Doherty
2026-12-03 09:44:02 -05:00
parent d12fd4f5a0
commit 31e16fbc80
19 changed files with 974 additions and 180 deletions
+7 -2
View File
@@ -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<MxEvent>`. 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.
+38 -1
View File
@@ -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
@@ -0,0 +1,83 @@
using ZB.MOM.WW.MxGateway.Client;
namespace ZB.MOM.WW.MxGateway.Client.Cli;
/// <summary>
/// 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.
/// </summary>
internal sealed class CliClientCache : IAsyncDisposable
{
private readonly Dictionary<string, IMxGatewayCliClient> _clients = [];
/// <summary>Gets the cached client for the options' connection settings, creating it on first use.</summary>
/// <param name="options">The connection options for this command.</param>
/// <param name="factory">Creates a client when none is cached.</param>
/// <returns>A lease that does not dispose the shared client.</returns>
public Lease Acquire(
MxGatewayClientOptions options,
Func<MxGatewayClientOptions, IMxGatewayCliClient> 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);
}
/// <summary>Disposes every cached client.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
public async ValueTask DisposeAsync()
{
foreach (IMxGatewayCliClient client in _clients.Values)
{
await client.DisposeAsync().ConfigureAwait(false);
}
_clients.Clear();
}
/// <summary>A client handed to one command; disposes it only when the command owns it.</summary>
internal sealed class Lease : IAsyncDisposable
{
private readonly bool _owned;
private Lease(IMxGatewayCliClient client, bool owned)
{
Client = client;
_owned = owned;
}
/// <summary>Gets the leased client.</summary>
public IMxGatewayCliClient Client { get; }
/// <summary>Wraps a client the command created and must dispose.</summary>
/// <param name="client">The client.</param>
/// <returns>The lease.</returns>
public static Lease Owned(IMxGatewayCliClient client) => new(client, owned: true);
/// <summary>Wraps a cache-owned client.</summary>
/// <param name="client">The client.</param>
/// <returns>The lease.</returns>
public static Lease Shared(IMxGatewayCliClient client) => new(client, owned: false);
/// <inheritdoc />
public ValueTask DisposeAsync() => _owned ? Client.DisposeAsync() : ValueTask.CompletedTask;
}
}
@@ -29,4 +29,55 @@ internal static class MxGatewayCliSecretRedactor
return redacted;
}
/// <summary>
/// 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 <c>0</c> turns
/// <c>0x80004005</c> into <c>[redacted]x8[redacted]...</c>).
/// </summary>
/// <param name="value">The message text to redact.</param>
/// <param name="tokens">The secret tokens to remove; null or empty entries are ignored.</param>
/// <returns>The value with whole-token occurrences replaced by a redacted placeholder.</returns>
public static string RedactTokens(string value, IEnumerable<string?> 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 == '_';
}
@@ -65,7 +65,8 @@ public static class MxGatewayClientCli
TextWriter standardError,
Func<MxGatewayClientOptions, IMxGatewayCliClient> 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<MxGatewayClientOptions, IMxGatewayCliClient> 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<string?> 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);
}
/// <summary>
/// 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)
{
@@ -112,18 +112,28 @@ internal sealed class FakeGatewayTransport(MxGatewayClientOptions options) : IMx
return Task.FromResult(OpenSessionReply);
}
/// <summary>
/// Gets or sets an optional behaviour run (before any queued exception) on each CloseSessionAsync call.
/// </summary>
public Func<CallOptions, Task>? CloseSessionBehavior { get; set; }
/// <inheritdoc />
public Task<CloseSessionReply> CloseSessionAsync(
public async Task<CloseSessionReply> 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;
}
/// <summary>
@@ -1413,8 +1413,7 @@ public sealed class MxGatewayClientCliTests
};
var sw = System.Diagnostics.Stopwatch.StartNew();
await Assert.ThrowsAsync<OperationCanceledException>(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();
}
/// <summary>Verifies batch mode builds one client for lines with identical connection options (CDN-011).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>Verifies a different connection configuration gets its own client in batch mode.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>Verifies a short --value does not garble the HRESULT in the error message (CDN-010).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>Verifies a secured-write payload is redacted as a whole token while the HRESULT survives.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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());
}
/// <summary>Verifies a command that times out reports an error line and exit code 1 instead of an unhandled exception (CDN-009).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>Fake CLI client for testing.</summary>
private sealed class FakeCliClient : IMxGatewayCliClient
{
@@ -0,0 +1,297 @@
using Grpc.Core;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
namespace ZB.MOM.WW.MxGateway.Client.Tests;
/// <summary>
/// Regression tests for the 2026-12-02 review, Phase 6: keepalive, error mapping, malformed
/// replies, and stream / channel lifecycle in the .NET client.
/// </summary>
public sealed class MxGatewayClientReviewPhase6Tests
{
/// <summary>Verifies the default handler sends HTTP/2 keepalive pings every 30 s, also with no active call (CDN-004).</summary>
[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);
}
/// <summary>Verifies the keepalive interval and timeout come from the client options on both clients.</summary>
[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);
}
/// <summary>Verifies non-positive keepalive values are rejected, and an infinite delay disables pings.</summary>
[Fact]
public void Options_ValidateKeepalive()
{
Assert.Throws<ArgumentOutOfRangeException>(
() => new MxGatewayClientOptions { Endpoint = new Uri("http://h:1"), ApiKey = "k", KeepAlivePingDelay = TimeSpan.Zero }.Validate());
Assert.Throws<ArgumentOutOfRangeException>(
() => 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();
}
/// <summary>Verifies a gateway-sent Cancelled status is not reported as caller cancellation (CDN-001).</summary>
[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<MxGatewayException>(mapped);
Assert.Equal(StatusCode.Cancelled, exception.GrpcStatusCode);
Assert.Same(rpc, exception.InnerException);
}
/// <summary>Verifies the caller's own cancellation still maps to OperationCanceledException.</summary>
[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<OperationCanceledException>(mapped);
}
/// <summary>Verifies NotFound and FailedPrecondition on the session API become the session-lost exception (CDN-002).</summary>
/// <param name="code">The gRPC status the gateway returned.</param>
[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<MxGatewaySessionException>(mapped);
Assert.Equal(code, exception.GrpcStatusCode);
}
/// <summary>Verifies the Galaxy Repository API, which has no sessions, keeps NotFound as a plain gateway exception.</summary>
[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());
}
/// <summary>Verifies ResourceExhausted is not retried (CDN-007).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<MxGatewayResourceExhaustedException>(
() => client.CloseSessionRawAsync(new CloseSessionRequest { SessionId = "s" }));
Assert.Single(transport.CloseSessionCalls);
}
/// <summary>Verifies Unavailable is still retried.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>Verifies an OK reply without the typed payload is a protocol error, not handle 0 (CDN-008).</summary>
/// <param name="kind">The command kind whose reply omits its payload.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<MxGatewayMalformedReplyException>(async () =>
{
_ = kind switch
{
MxCommandKind.Register => await session.RegisterAsync("c"),
MxCommandKind.AddItem => await session.AddItemAsync(1, "Tag.A"),
_ => await session.AddItem2Async(1, "Tag.A", "ctx"),
};
});
}
/// <summary>Verifies an int32 return_value is still accepted when the typed payload is absent.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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"));
}
/// <summary>Verifies disposing an event stream while a read is in flight neither throws nor hangs (CDN-003).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<OperationCanceledException>(() => reader);
}
}
/// <summary>Verifies the dispose-time session close is bounded and swallows cancellation (CDN-005).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>Verifies a cancellation surfaced by the close does not escape dispose.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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();
}
/// <summary>Verifies disposing an owned client closes the connection to the gateway (CDN-006).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<ObjectDisposedException>(
() => ((HttpMessageInvoker)invoker).SendAsync(
new HttpRequestMessage(HttpMethod.Get, server.Endpoint),
CancellationToken.None));
}
private static async IAsyncEnumerable<MxEvent> 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());
}
@@ -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;
/// <summary>
@@ -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);
}
/// <summary>
@@ -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);
/// <summary>Creates the <see cref="SocketsHttpHandler"/> used for gRPC calls, exposed for test configuration.</summary>
/// <param name="options">The client options supplying TLS and timeout settings.</param>
/// <returns>The configured HTTP handler.</returns>
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;
}
/// <summary>
/// Creates the <see cref="SocketsHttpHandler"/> used for gRPC calls; exposed internally so tests can inspect it.
/// </summary>
/// <param name="options">The client options that configure connect timeout, keepalive, and TLS behavior.</param>
/// <returns>A configured <see cref="SocketsHttpHandler"/>.</returns>
internal static SocketsHttpHandler CreateHttpHandlerForTests(MxGatewayClientOptions options) =>
GatewayHttpHandlerFactory.Create(options, out _);
private void ThrowIfDisposed()
{
@@ -0,0 +1,81 @@
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
namespace ZB.MOM.WW.MxGateway.Client;
/// <summary>
/// Builds the <see cref="SocketsHttpHandler"/> shared by <see cref="MxGatewayClient"/> and
/// <see cref="GalaxyRepositoryClient"/>: connect timeout, HTTP/2 keepalive, and TLS pinning.
/// </summary>
internal static class GatewayHttpHandlerFactory
{
/// <summary>
/// Creates the handler for an owned channel.
/// </summary>
/// <param name="options">The client options supplying keepalive, connect timeout, and TLS settings.</param>
/// <param name="trustedRoot">
/// The pinned CA certificate captured by the validation callback, or <see langword="null"/> when none is pinned.
/// The caller disposes it after the handler is disposed.
/// </param>
/// <returns>The configured handler.</returns>
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;
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -0,0 +1,53 @@
using Grpc.Core;
namespace ZB.MOM.WW.MxGateway.Client;
/// <summary>
/// Maps a transport-level <see cref="RpcException"/> to the client's exception types. Shared by
/// the session and Galaxy Repository transports so the two cannot drift apart.
/// </summary>
internal static class GrpcStatusMapper
{
/// <summary>
/// Maps <paramref name="exception"/>. The original gRPC status stays reachable through
/// <see cref="MxGatewayException.GrpcStatusCode"/> and the inner exception.
/// </summary>
/// <param name="exception">The gRPC failure.</param>
/// <param name="cancellationToken">The caller's token.</param>
/// <param name="sessionScoped">
/// <see langword="true"/> for the session API, where <c>NotFound</c> / <c>FailedPrecondition</c>
/// mean the session is gone or not ready; the Galaxy Repository has no sessions.
/// </param>
/// <returns>The exception to throw.</returns>
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),
};
}
}
@@ -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;
/// <summary>
@@ -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);
}
/// <summary>
@@ -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);
/// <summary>
/// Creates the <see cref="SocketsHttpHandler"/> used for gRPC calls; exposed internally so tests can inspect it.
/// </summary>
/// <param name="options">The client options that configure connect timeout and TLS behavior.</param>
/// <param name="options">The client options that configure connect timeout, keepalive, and TLS behavior.</param>
/// <returns>A configured <see cref="SocketsHttpHandler"/>.</returns>
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()
{
@@ -45,6 +45,20 @@ public sealed class MxGatewayClientOptions
/// </summary>
public TimeSpan ConnectTimeout { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>
/// 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 <see cref="Timeout.InfiniteTimeSpan"/> to disable.
/// </summary>
public TimeSpan KeepAlivePingDelay { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>
/// Gets how long to wait for a keepalive ping acknowledgement before the connection is
/// considered dead and in-flight calls fail (default 10 s).
/// </summary>
public TimeSpan KeepAlivePingTimeout { get; init; } = TimeSpan.FromSeconds(10);
/// <summary>
/// Gets the default timeout for unary gRPC calls.
/// </summary>
@@ -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(
@@ -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;
}
}
@@ -18,6 +18,10 @@ public sealed class MxGatewayEventStream : IAsyncDisposable
{
private readonly IAsyncEnumerator<MxEvent> _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();
}
}
@@ -55,6 +55,13 @@ public class MxGatewayException : Exception
Statuses = statuses;
}
/// <summary>
/// Gets the gRPC status code of the failed call when this exception wraps an
/// <see cref="Grpc.Core.RpcException"/>, otherwise <see langword="null"/>. Lets a caller tell
/// "deadline exceeded" from "gateway unavailable" without digging into the inner exception.
/// </summary>
public Grpc.Core.StatusCode? GrpcStatusCode => (InnerException as Grpc.Core.RpcException)?.StatusCode;
/// <summary>
/// Gets the session ID associated with the exception, if available.
/// </summary>
@@ -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");
}
/// <summary>
@@ -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");
}
/// <summary>
@@ -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");
}
/// <summary>
@@ -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