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.
This commit is contained in:
@@ -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.
|
||||
|
||||
|
||||
+18
-20
@@ -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
|
||||
|
||||
|
||||
@@ -56,4 +56,19 @@ public sealed class HResultConverterTests
|
||||
Assert.Contains("0x", converted.DiagnosticMessage);
|
||||
Assert.DoesNotContain("do not include this", converted.DiagnosticMessage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WIP-005: a worker-side validation failure maps to INVALID_REQUEST and
|
||||
/// carries no HRESULT.
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,7 +115,17 @@ public sealed class VariantConverterTests
|
||||
[Fact]
|
||||
public void ConvertToComValue_WithNoKind_Throws()
|
||||
{
|
||||
Assert.Throws<ArgumentException>(() => _converter.ConvertToComValue(new MxValue()));
|
||||
Assert.Throws<WorkerRequestValidationException>(() => _converter.ConvertToComValue(new MxValue()));
|
||||
}
|
||||
|
||||
/// <summary>WIP-005: a raw payload and an empty array are worker-side validation failures too.</summary>
|
||||
[Fact]
|
||||
public void ConvertToComValue_WithRawOrEmptyArray_ThrowsValidationException()
|
||||
{
|
||||
Assert.Throws<WorkerRequestValidationException>(
|
||||
() => _converter.ConvertToComValue(new MxValue { RawValue = ByteString.CopyFromUtf8("x") }));
|
||||
Assert.Throws<WorkerRequestValidationException>(
|
||||
() => _converter.ConvertToComValue(new MxValue { ArrayValue = new MxArray() }));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that file time values with expected time data type are converted to protobuf timestamps.</summary>
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WIP-005: the interop raises an MXAccess E_INVALIDARG as a plain
|
||||
/// ArgumentException; that stays an MXAccess failure with its HRESULT.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies cancellation before execution prevents the command from running.
|
||||
/// </summary>
|
||||
|
||||
@@ -15,13 +15,31 @@ public sealed class HResultConversion
|
||||
string diagnosticMessage)
|
||||
{
|
||||
HResult = hresult;
|
||||
HasHResult = true;
|
||||
ProtocolStatus = protocolStatus;
|
||||
DiagnosticMessage = diagnosticMessage;
|
||||
}
|
||||
|
||||
/// <summary>The original HResult value.</summary>
|
||||
/// <summary>Initializes a conversion result that carries no HResult.</summary>
|
||||
/// <param name="protocolStatus">The converted protocol status.</param>
|
||||
/// <param name="diagnosticMessage">Diagnostic message describing the failure.</param>
|
||||
public HResultConversion(
|
||||
ProtocolStatus protocolStatus,
|
||||
string diagnosticMessage)
|
||||
{
|
||||
ProtocolStatus = protocolStatus;
|
||||
DiagnosticMessage = diagnosticMessage;
|
||||
}
|
||||
|
||||
/// <summary>The original HResult value; zero when <see cref="HasHResult"/> is false.</summary>
|
||||
public int HResult { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Whether the failure carries an HResult. False for a request the worker
|
||||
/// rejected before any MXAccess call, which must not report one.
|
||||
/// </summary>
|
||||
public bool HasHResult { get; }
|
||||
|
||||
/// <summary>The converted protocol status.</summary>
|
||||
public ProtocolStatus ProtocolStatus { get; }
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Worker.Conversion;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="ArgumentException"/> for an <c>E_INVALIDARG</c>
|
||||
/// returned by MXAccess itself; that one is an MXAccess failure and keeps
|
||||
/// its HRESULT, while this one maps to <c>INVALID_REQUEST</c> with no
|
||||
/// HRESULT (WIP-005, decision D9).
|
||||
/// </summary>
|
||||
public sealed class WorkerRequestValidationException : ArgumentException
|
||||
{
|
||||
/// <summary>Initializes a new instance of the <see cref="WorkerRequestValidationException"/> class.</summary>
|
||||
/// <param name="message">Why the request was rejected.</param>
|
||||
/// <param name="paramName">The rejected parameter.</param>
|
||||
public WorkerRequestValidationException(string message, string paramName)
|
||||
: base(message, paramName)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user