From 9adea04b37ecfb3b0784ae2f07891ed7d0c62c51 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:45:14 -0500 Subject: [PATCH] fix(worker): report worker-side validation and STA shutdown without an MXAccess HRESULT (WIP-005, #255) Per D9: a request the worker rejects before calling MXAccess (write value with no kind, raw payload, empty MxArray) throws the new WorkerRequestValidationException and replies INVALID_REQUEST with no HRESULT. A plain ArgumentException stays MXACCESS_FAILURE with its HRESULT, because the interop raises MXAccess E_INVALIDARG that way. The dispatcher now converts executor exceptions on the STA, so anything the InvokeAsync await throws is the runtime refusing the work item (shutdown, disposal, dead loop, canceled at shutdown) and replies WORKER_UNAVAILABLE. No .proto change. Status mapping documented in docs/WorkerConversion.md. --- docs/MxAccessWorkerInstanceDesign.md | 5 +- docs/WorkerConversion.md | 38 +++++------ .../Conversion/HResultConverterTests.cs | 15 +++++ .../Conversion/VariantConverterTests.cs | 12 +++- .../Sta/StaCommandDispatcherTests.cs | 65 +++++++++++++++++++ .../Conversion/HResultConversion.cs | 20 +++++- .../Conversion/HResultConverter.cs | 23 ++++++- .../Conversion/VariantConverter.cs | 8 +-- .../WorkerRequestValidationException.cs | 23 +++++++ .../Sta/StaCommandDispatcher.cs | 30 ++++++++- 10 files changed, 207 insertions(+), 32 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Worker/Conversion/WorkerRequestValidationException.cs diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index d91394fa..ac0f3248 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -744,7 +744,10 @@ Parity tests need stable command-specific request and reply shapes. Both commands set `Hresult` to `0` only after the COM call returns normally. COM exceptions flow through `StaCommandDispatcher`, which captures the thrown -HRESULT and converts the reply to `ProtocolStatusCode.MxaccessFailure`. +HRESULT and converts the reply to `ProtocolStatusCode.MxaccessFailure`. A request +the worker rejects before calling MXAccess replies `InvalidRequest` with no +HRESULT, and a work item the STA runtime refuses at shutdown replies +`WorkerUnavailable`; see the status mapping in `WorkerConversion.md`. `MxAccessStaSession.GetRegisteredServerHandlesAsync` returns an STA-read snapshot of tracked server handles for diagnostics and future cleanup logic. diff --git a/docs/WorkerConversion.md b/docs/WorkerConversion.md index c545651e..7aff5cbf 100644 --- a/docs/WorkerConversion.md +++ b/docs/WorkerConversion.md @@ -129,38 +129,36 @@ The MXAccess engine returns values whose semantic type only fully resolves after ## HResultConverter and HResultConversion -`HResultConverter.Convert` wraps any `Exception` thrown across the COM boundary. It prefers `COMException.ErrorCode` over `Exception.HResult` because the runtime sometimes overwrites `Exception.HResult` while marshalling, and the `ErrorCode` field is the value the COM call actually returned. +`HResultConverter.Convert` turns an exception the command executor threw into a reply status. It prefers `COMException.ErrorCode` over `Exception.HResult` because the runtime sometimes overwrites `Exception.HResult` while marshalling, and the `ErrorCode` field is the value the COM call actually returned. -```csharp -public HResultConversion Convert(Exception exception) -{ - if (exception is null) - { - throw new ArgumentNullException(nameof(exception)); - } +### Status mapping - int hresult = exception is COMException comException - ? comException.ErrorCode - : exception.HResult; +The reply status says who failed. A client must be able to tell a request it built wrongly, a worker that is going away, and MXAccess rejecting the call apart, and an HRESULT is reported only when MXAccess produced one. - return new HResultConversion( - hresult, - CreateProtocolStatus(hresult, exception), - CreateSafeDiagnosticMessage(exception)); -} -``` +| Failure | `ProtocolStatusCode` | `hresult` | +|---------|----------------------|-----------| +| `WorkerRequestValidationException`: the worker rejected the request before any MXAccess call (a write value with no kind, a raw payload, an `MxArray` with no values) | `INVALID_REQUEST` | not set | +| The STA runtime refused or dropped the work item: shut down, disposed, the STA loop died, or a queued item was canceled at shutdown | `WORKER_UNAVAILABLE` | not set | +| `COMException` from an MXAccess call | `MXACCESS_FAILURE` | `COMException.ErrorCode` | +| `ArgumentException` from an MXAccess call (the interop raises `E_INVALIDARG`, `0x80070057`, as `ArgumentException`) | `MXACCESS_FAILURE` | `0x80070057` | +| Any other exception from the executor | `MXACCESS_FAILURE` | `Exception.HResult` | + +`WorkerRequestValidationException` derives from `ArgumentException` but is a separate type because a plain `ArgumentException` is ambiguous: the interop raises one for an MXAccess `E_INVALIDARG` (for example `Suspend` on an item that is added but not advised), and that one is MXAccess parity and keeps its HRESULT. Before this split a malformed write reported `MXACCESS_FAILURE` with `0x80070057`, which is the same answer MXAccess gives for a bad argument, so the operator went looking at the Galaxy attribute (WIP-005, decision D9 in the 2026-12-02 review plan). No `.proto` change was needed: both codes already existed, and clients already handle a reply without an HRESULT. + +`StaCommandDispatcher` keeps the two failure sources apart structurally. The executor runs inside a wrapper on the STA that converts its exceptions to replies through `HResultConverter`, so any exception the `StaRuntime.InvokeAsync` await itself throws can only come from the runtime, and the dispatcher answers it with `WORKER_UNAVAILABLE`. The dispatcher's own shutdown and queue-full rejections were already `WORKER_UNAVAILABLE`. `CreateProtocolStatus` maps `0` (`S_OK`) to `ProtocolStatusCode.Ok` and any non-zero HRESULT to `ProtocolStatusCode.MxaccessFailure`. The status `Message` includes the exception type name and the formatted HRESULT (`HRESULT 0x<8 hex digits>`), giving downstream operators the same identifier they would see in COM event logs. -`HResultConversion` is an immutable carrier with three fields: +`HResultConversion` is an immutable carrier: | Field | Purpose | |-------|---------| -| `HResult` | Raw signed 32-bit HRESULT, suitable for inclusion in a wire reply | +| `HResult` | Raw signed 32-bit HRESULT, suitable for inclusion in a wire reply; zero when `HasHResult` is false | +| `HasHResult` | False for a worker-side validation failure, so the reply leaves `hresult` unset | | `ProtocolStatus` | The `ProtocolStatus` projection used in command replies | | `DiagnosticMessage` | A safe, fully-qualified diagnostic string for logs | -The diagnostic message is built from the exception type's `FullName` and the formatted HRESULT only. It deliberately omits `Exception.Message` so user-supplied or localized strings do not leak into worker log channels that may be shipped to less trusted destinations. +For an MXAccess failure the diagnostic message is built from the exception type's `FullName` and the formatted HRESULT only. It deliberately omits `Exception.Message` so user-supplied or localized strings do not leak into worker log channels that may be shipped to less trusted destinations. A validation failure's message is the worker's own fixed text and never contains a value, so it is included. ## MxStatusProxyConverter diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs index 892ab29d..12a5ef75 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/HResultConverterTests.cs @@ -56,4 +56,19 @@ public sealed class HResultConverterTests Assert.Contains("0x", converted.DiagnosticMessage); Assert.DoesNotContain("do not include this", converted.DiagnosticMessage); } + + /// + /// WIP-005: a worker-side validation failure maps to INVALID_REQUEST and + /// carries no HRESULT. + /// + [Fact] + public void Convert_WithWorkerRequestValidationException_ReturnsInvalidRequestWithoutHResult() + { + HResultConversion converted = _converter.Convert( + new WorkerRequestValidationException("MxValue has no value kind set; nothing to write.", "value")); + + Assert.False(converted.HasHResult); + Assert.Equal(ProtocolStatusCode.InvalidRequest, converted.ProtocolStatus.Code); + Assert.DoesNotContain("0x80070057", converted.DiagnosticMessage); + } } diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs index d7a8e7a2..3f8eff10 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Conversion/VariantConverterTests.cs @@ -115,7 +115,17 @@ public sealed class VariantConverterTests [Fact] public void ConvertToComValue_WithNoKind_Throws() { - Assert.Throws(() => _converter.ConvertToComValue(new MxValue())); + Assert.Throws(() => _converter.ConvertToComValue(new MxValue())); + } + + /// WIP-005: a raw payload and an empty array are worker-side validation failures too. + [Fact] + public void ConvertToComValue_WithRawOrEmptyArray_ThrowsValidationException() + { + Assert.Throws( + () => _converter.ConvertToComValue(new MxValue { RawValue = ByteString.CopyFromUtf8("x") })); + Assert.Throws( + () => _converter.ConvertToComValue(new MxValue { ArrayValue = new MxArray() })); } /// Verifies that file time values with expected time data type are converted to protobuf timestamps. diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs index e3dffbef..7f4ad4ba 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/Sta/StaCommandDispatcherTests.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using ZB.MOM.WW.MxGateway.Contracts.Proto; using ZB.MOM.WW.MxGateway.Worker.Bootstrap; +using ZB.MOM.WW.MxGateway.Worker.Conversion; using ZB.MOM.WW.MxGateway.Worker.Sta; using ZB.MOM.WW.MxGateway.Worker.Tests.Bootstrap; using ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport; @@ -65,6 +66,70 @@ public sealed class StaCommandDispatcherTests Assert.DoesNotContain("provider detail", reply.DiagnosticMessage); } + /// + /// WIP-005: a request the worker rejects before calling MXAccess replies + /// INVALID_REQUEST with no HRESULT, so it cannot be mistaken for MXAccess + /// returning E_INVALIDARG. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DispatchAsync_WhenExecutorRejectsRequest_ReturnsInvalidRequestWithoutHResult() + { + using StaRuntime runtime = CreateRuntime(); + runtime.Start(); + StaCommandDispatcher dispatcher = new( + runtime, + new ThrowingCommandExecutor(new WorkerRequestValidationException("MxValue has no value kind set; nothing to write.", "value"))); + + MxCommandReply reply = await dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Write)); + + Assert.Equal(ProtocolStatusCode.InvalidRequest, reply.ProtocolStatus.Code); + Assert.False(reply.HasHresult); + Assert.Equal("correlation-1", reply.CorrelationId); + } + + /// + /// WIP-005: the interop raises an MXAccess E_INVALIDARG as a plain + /// ArgumentException; that stays an MXAccess failure with its HRESULT. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DispatchAsync_WhenMxAccessRaisesInvalidArg_KeepsMxAccessFailureWithHResult() + { + using StaRuntime runtime = CreateRuntime(); + runtime.Start(); + StaCommandDispatcher dispatcher = new( + runtime, + new ThrowingCommandExecutor(new ArgumentException("The parameter is incorrect."))); + + MxCommandReply reply = await dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Suspend)); + + Assert.Equal(ProtocolStatusCode.MxaccessFailure, reply.ProtocolStatus.Code); + Assert.True(reply.HasHresult); + Assert.Equal(unchecked((int)0x80070057), reply.Hresult); + } + + /// + /// WIP-005: when the STA runtime itself refuses the work item (shut down + /// underneath the dispatcher), the reply is WORKER_UNAVAILABLE with no + /// HRESULT rather than an MXAccess failure carrying a CLR HRESULT. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task DispatchAsync_WhenStaRuntimeShutDown_ReturnsWorkerUnavailableWithoutHResult() + { + using StaRuntime runtime = CreateRuntime(); + runtime.Start(); + StaCommandDispatcher dispatcher = new(runtime, new RecordingCommandExecutor()); + Assert.True(runtime.Shutdown(TimeSpan.FromSeconds(5))); + + MxCommandReply reply = await dispatcher.DispatchAsync(CreateCommand("correlation-1", MxCommandKind.Register)); + + Assert.Equal(ProtocolStatusCode.WorkerUnavailable, reply.ProtocolStatus.Code); + Assert.False(reply.HasHresult); + Assert.Equal("correlation-1", reply.CorrelationId); + } + /// /// Verifies cancellation before execution prevents the command from running. /// diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs index ea128942..82b7fffe 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConversion.cs @@ -15,13 +15,31 @@ public sealed class HResultConversion string diagnosticMessage) { HResult = hresult; + HasHResult = true; ProtocolStatus = protocolStatus; DiagnosticMessage = diagnosticMessage; } - /// The original HResult value. + /// Initializes a conversion result that carries no HResult. + /// The converted protocol status. + /// Diagnostic message describing the failure. + public HResultConversion( + ProtocolStatus protocolStatus, + string diagnosticMessage) + { + ProtocolStatus = protocolStatus; + DiagnosticMessage = diagnosticMessage; + } + + /// The original HResult value; zero when is false. public int HResult { get; } + /// + /// Whether the failure carries an HResult. False for a request the worker + /// rejected before any MXAccess call, which must not report one. + /// + public bool HasHResult { get; } + /// The converted protocol status. public ProtocolStatus ProtocolStatus { get; } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs index b46ece0c..dd3c635e 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/HResultConverter.cs @@ -16,6 +16,23 @@ public sealed class HResultConverter throw new ArgumentNullException(nameof(exception)); } + if (exception is WorkerRequestValidationException) + { + // The worker rejected the request before calling MXAccess, so no + // MXAccess HRESULT exists. Reporting the CLR one (0x80070057) would + // be indistinguishable from MXAccess returning E_INVALIDARG + // (WIP-005, decision D9). + return new HResultConversion( + new ProtocolStatus + { + Code = ProtocolStatusCode.InvalidRequest, + Message = exception.Message, + }, + CreateSafeDiagnosticMessage(exception, includeHResult: false)); + } + + // A COMException, and an ArgumentException the interop raises for an + // MXAccess E_INVALIDARG, are MXAccess failures and keep the HRESULT. int hresult = exception is COMException comException ? comException.ErrorCode : exception.HResult; @@ -43,9 +60,11 @@ public sealed class HResultConverter }; } - private static string CreateSafeDiagnosticMessage(Exception exception) + private static string CreateSafeDiagnosticMessage(Exception exception, bool includeHResult = true) { - return $"{exception.GetType().FullName}: {FormatHResult(exception.HResult)}"; + return includeHResult + ? $"{exception.GetType().FullName}: {FormatHResult(exception.HResult)}" + : $"{exception.GetType().FullName}: {exception.Message}"; } private static string FormatHResult(int hresult) diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs index 1827502c..26993def 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/VariantConverter.cs @@ -286,9 +286,9 @@ public sealed class VariantConverter // it as the timestamped-write time argument. MxValue.KindOneofCase.TimestampValue => value.TimestampValue.ToDateTime(), MxValue.KindOneofCase.ArrayValue => ConvertToComArray(value.ArrayValue), - MxValue.KindOneofCase.RawValue => throw new ArgumentException( + MxValue.KindOneofCase.RawValue => throw new WorkerRequestValidationException( "MxValue raw payloads cannot be written to MXAccess.", nameof(value)), - _ => throw new ArgumentException( + _ => throw new WorkerRequestValidationException( "MxValue has no value kind set; nothing to write.", nameof(value)), }; } @@ -368,9 +368,9 @@ public sealed class VariantConverter MxArray.ValuesOneofCase.StringValues => array.StringValues.Values.ToArray(), MxArray.ValuesOneofCase.TimestampValues => array.TimestampValues.Values.Select(timestamp => timestamp.ToDateTime()).ToArray(), - MxArray.ValuesOneofCase.RawValues => throw new ArgumentException( + MxArray.ValuesOneofCase.RawValues => throw new WorkerRequestValidationException( "MxArray raw payloads cannot be written to MXAccess.", nameof(array)), - _ => throw new ArgumentException( + _ => throw new WorkerRequestValidationException( "MxArray has no element values set; nothing to write.", nameof(array)), }; } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Conversion/WorkerRequestValidationException.cs b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/WorkerRequestValidationException.cs new file mode 100644 index 00000000..4c0d1e0b --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Worker/Conversion/WorkerRequestValidationException.cs @@ -0,0 +1,23 @@ +using System; + +namespace ZB.MOM.WW.MxGateway.Worker.Conversion; + +/// +/// Thrown when the worker rejects a request it built from the command +/// payload before any MXAccess call is made, for example a write value with +/// no kind set. The dedicated type exists because the MXAccess interop +/// raises for an E_INVALIDARG +/// returned by MXAccess itself; that one is an MXAccess failure and keeps +/// its HRESULT, while this one maps to INVALID_REQUEST with no +/// HRESULT (WIP-005, decision D9). +/// +public sealed class WorkerRequestValidationException : ArgumentException +{ + /// Initializes a new instance of the class. + /// Why the request was rejected. + /// The rejected parameter. + public WorkerRequestValidationException(string message, string paramName) + : base(message, paramName) + { + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs index 9ef6a74f..1a6eb2d6 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Sta/StaCommandDispatcher.cs @@ -284,15 +284,23 @@ public sealed class StaCommandDispatcher MxCommandReply completedReply; try { + // The executor's own exceptions are turned into replies on the STA, + // so anything InvokeAsync itself throws is the runtime refusing or + // dropping the work item: shutdown, disposal, a dead STA loop, or a + // queued item canceled at shutdown. None of those is an MXAccess + // failure, and none carries an MXAccess HRESULT (WIP-005, D9). MxCommandReply reply = await staRuntime - .InvokeAsync(() => commandExecutor.Execute(command)) + .InvokeAsync(() => ExecuteOnSta(command)) .ConfigureAwait(false); completedReply = NormalizeReply(command, reply); } catch (Exception exception) { - completedReply = CreateExceptionReply(command, exception); + completedReply = CreateRejectedReply( + command, + ProtocolStatusCode.WorkerUnavailable, + $"The worker STA runtime is unavailable ({exception.GetType().Name})."); } finally { @@ -406,6 +414,18 @@ public sealed class StaCommandDispatcher return reply; } + private MxCommandReply ExecuteOnSta(StaCommand command) + { + try + { + return commandExecutor.Execute(command); + } + catch (Exception exception) + { + return CreateExceptionReply(command, exception); + } + } + private MxCommandReply CreateExceptionReply( StaCommand command, Exception exception) @@ -413,7 +433,11 @@ public sealed class StaCommandDispatcher HResultConversion conversion = hresultConverter.Convert(exception); MxCommandReply reply = CreateBaseReply(command); reply.ProtocolStatus = conversion.ProtocolStatus; - reply.Hresult = conversion.HResult; + if (conversion.HasHResult) + { + reply.Hresult = conversion.HResult; + } + reply.DiagnosticMessage = conversion.DiagnosticMessage; return reply;