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:
@@ -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