Merge fix/review-2026-12-phase4 (2026-12-02 review fix plan)

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:43 -05:00
13 changed files with 783 additions and 178 deletions
@@ -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>
@@ -229,6 +239,117 @@ public sealed class VariantConverterTests
converted.ArrayValue.TimestampValues.Values);
}
/// <summary>WIP-003: a string element in a Time array is parsed as MXAccess local time, not thrown on.</summary>
[Fact]
public void ConvertArray_WithExpectedTimeAndStringElement_ParsesLocalTime()
{
DateTime local = new(2026, 3, 26, 13, 38, 22, DateTimeKind.Local);
string text = local.ToString(System.Globalization.CultureInfo.CurrentCulture);
MxArray converted = _converter.ConvertArray(new object[] { text }, MxDataType.Time);
Assert.Equal(MxDataType.Time, converted.ElementDataType);
Assert.Equal(ProtobufTimestamp.FromDateTime(local.ToUniversalTime()), converted.TimestampValues.Values[0]);
}
/// <summary>WIP-003: an unparseable string element falls back to the raw projection naming the element.</summary>
[Fact]
public void ConvertArray_WithExpectedTimeAndBadString_FallsBackToRaw()
{
MxArray converted = _converter.ConvertArray(new object[] { "not a time" }, MxDataType.Time);
Assert.Equal(MxDataType.Unknown, converted.ElementDataType);
Assert.Equal((int)MxDataType.Time, converted.RawElementDataType);
Assert.Equal(MxArray.ValuesOneofCase.RawValues, converted.ValuesCase);
Assert.Contains("element 0", converted.RawDiagnostic);
Assert.DoesNotContain("not a time", converted.RawDiagnostic);
}
/// <summary>WIP-003: an out-of-range FILETIME in a long[] falls back to the array's own Integer projection.</summary>
[Fact]
public void ConvertArray_WithExpectedTimeAndNegativeFileTime_FallsBackToInt64()
{
MxArray converted = _converter.ConvertArray(new[] { -1L, 5L }, MxDataType.Time);
Assert.Equal(MxDataType.Integer, converted.ElementDataType);
Assert.Equal(new[] { -1L, 5L }, converted.Int64Values.Values);
Assert.Contains("element 0", converted.RawDiagnostic);
}
/// <summary>WIP-003: a double element is not read as a FILETIME near 1601.</summary>
[Fact]
public void ConvertArray_WithExpectedTimeAndDoubleElement_DoesNotProjectFileTime()
{
MxArray converted = _converter.ConvertArray(new[] { 46107.5d }, MxDataType.Time);
Assert.Equal(MxDataType.Double, converted.ElementDataType);
Assert.Equal(new[] { 46107.5d }, converted.DoubleValues.Values);
}
/// <summary>WIP-003: an unconvertible element in a Boolean array falls back to raw rather than throwing.</summary>
[Fact]
public void ConvertArray_WithExpectedBooleanAndBadString_FallsBackToRaw()
{
MxArray converted = _converter.ConvertArray(new object[] { true, "x" }, MxDataType.Boolean);
Assert.Equal(MxArray.ValuesOneofCase.RawValues, converted.ValuesCase);
Assert.Contains("element 1", converted.RawDiagnostic);
}
/// <summary>WIP-003: scalar FILETIMEs outside the DateTime range stay integers instead of throwing.</summary>
[Fact]
public void Convert_WithExpectedTimeAndOutOfRangeFileTime_ProjectsInteger()
{
MxValue negative = _converter.Convert(-1L, MxDataType.Time);
MxValue huge = _converter.Convert((ulong)long.MaxValue, MxDataType.Time);
Assert.Equal(MxDataType.Integer, negative.DataType);
Assert.Equal(-1L, negative.Int64Value);
Assert.False(string.IsNullOrEmpty(negative.RawDiagnostic));
Assert.Equal(MxDataType.Integer, huge.DataType);
Assert.Equal(long.MaxValue, huge.Int64Value);
}
/// <summary>WIP-004: a uint[] is widened to Int64 like a scalar uint.</summary>
[Fact]
public void ConvertArray_WithUInt32Array_WidensToInt64()
{
MxArray converted = _converter.ConvertArray(new[] { uint.MaxValue, 1u });
Assert.Equal(MxDataType.Integer, converted.ElementDataType);
Assert.Equal(new[] { (long)uint.MaxValue, 1L }, converted.Int64Values.Values);
}
/// <summary>WIP-004: a VARIANT array with a 64-bit element under an Integer hint widens instead of overflowing.</summary>
[Fact]
public void ConvertArray_WithObjectArrayAndWideInteger_WidensToInt64()
{
MxArray converted = _converter.ConvertArray(new object[] { 1, 5_000_000_000L }, MxDataType.Integer);
Assert.Equal(MxDataType.Integer, converted.ElementDataType);
Assert.Equal(new[] { 1L, 5_000_000_000L }, converted.Int64Values.Values);
}
/// <summary>WIP-004: an object[] of small integers keeps the Int32 projection.</summary>
[Fact]
public void ConvertArray_WithObjectArrayAndNarrowIntegers_KeepsInt32()
{
MxArray converted = _converter.ConvertArray(new object[] { 1, (short)2 }, MxDataType.Integer);
Assert.Equal(new[] { 1, 2 }, converted.Int32Values.Values);
}
/// <summary>WIP-004: a ulong above long.MaxValue mirrors the scalar raw fallback.</summary>
[Fact]
public void ConvertArray_WithUInt64AboveInt64Range_FallsBackToRaw()
{
MxArray converted = _converter.ConvertArray(new[] { ulong.MaxValue });
Assert.Equal(MxDataType.Unknown, converted.ElementDataType);
Assert.Equal(MxArray.ValuesOneofCase.RawValues, converted.ValuesCase);
Assert.Equal(ByteString.CopyFromUtf8(ulong.MaxValue.ToString(System.Globalization.CultureInfo.InvariantCulture)), converted.RawValues.Values[0]);
}
/// <summary>Verifies that unknown scalar types preserve raw value and diagnostic metadata.</summary>
[Fact]
public void Convert_WithUnknownScalar_PreservesRawMetadata()
@@ -95,6 +95,62 @@ public sealed class MxAccessBaseEventSinkTests
Assert.Equal(timestamp, cached.SourceTimestamp.ToDateTime());
}
/// <summary>
/// MXA-004: an OnDataChange or OnWriteComplete that MXAccess had already
/// queued on the STA is dispatched after <c>RemoveItem</c> evicted the
/// handle. The unbound sink (see <see cref="OnDataChange_ComCallback_PopulatesValueCache"/>)
/// records such a callback for any handle, which re-creates an entry nothing
/// evicts again because item handles are not reused within a registration.
/// Once bound to the session's registry, the sink must still forward the
/// event but leave both caches untouched for a removed handle.
/// </summary>
[Fact]
public void LateCallbacks_ForRemovedItemHandle_AreForwardedButNotCached()
{
MxAccessEventQueue queue = new();
MxAccessValueCache cache = new();
MxAccessWriteCompletionCache completionCache = new();
MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper(), cache, completionCache);
MxAccessHandleRegistry registry = new();
registry.RegisterServerHandle(7, "client");
registry.RegisterItemHandle(7, 21, "Tag.A", string.Empty, hasItemContext: false);
sink.BindHandleRegistry(registry);
MXSTATUS_PROXY[] statuses = Array.Empty<MXSTATUS_PROXY>();
registry.RemoveItemHandle(7, 21);
sink.OnDataChange(7, 21, 1234, 192, new DateTime(2026, 5, 18, 9, 15, 0, DateTimeKind.Utc), ref statuses);
sink.OnWriteComplete(7, 21, ref statuses);
Assert.Equal(2, queue.Count);
Assert.False(cache.TryGet(7, 21, out _));
Assert.Equal(0UL, completionCache.CurrentVersion(7, 21));
}
/// <summary>
/// The registry check must not suppress caching for a handle the session
/// still holds.
/// </summary>
[Fact]
public void Callbacks_ForLiveItemHandle_AreCachedWhenRegistryBound()
{
MxAccessEventQueue queue = new();
MxAccessValueCache cache = new();
MxAccessWriteCompletionCache completionCache = new();
MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper(), cache, completionCache);
MxAccessHandleRegistry registry = new();
registry.RegisterServerHandle(7, "client");
registry.RegisterItemHandle(7, 21, "Tag.A", string.Empty, hasItemContext: false);
sink.BindHandleRegistry(registry);
MXSTATUS_PROXY[] statuses = Array.Empty<MXSTATUS_PROXY>();
sink.OnDataChange(7, 21, 1234, 192, new DateTime(2026, 5, 18, 9, 15, 0, DateTimeKind.Utc), ref statuses);
sink.OnWriteComplete(7, 21, ref statuses);
Assert.True(cache.TryGet(7, 21, out MxAccessValueCache.CachedValue cached));
Assert.Equal(1234, cached.Value.Int32Value);
Assert.Equal(1UL, completionCache.CurrentVersion(7, 21));
}
/// <summary>
/// Verifies that the sink-bound <c>ValueCache</c> is exposed for sharing with
/// the owning <see cref="MxAccessSession"/> so writes and reads see the same
@@ -252,4 +308,38 @@ public sealed class MxAccessBaseEventSinkTests
Assert.Equal(13, mxEvent.ItemHandle);
Assert.Equal(integerDataTypeCode, mxEvent.OnBufferedDataChange.RawDataType);
}
/// <summary>
/// WIP-003: a multi-sample OnBufferedDataChange whose timestamp array holds
/// BSTR strings (the shape MXAccess uses for the OnDataChange timestamp) and
/// whose value array holds a value that does not fit the declared type must
/// still produce an event; a conversion throw would fault the session.
/// </summary>
[Fact]
public void OnBufferedDataChange_WithStringTimestampsAndBadValue_EnqueuesWithoutFault()
{
MxAccessEventQueue queue = new();
MxAccessBaseEventSink sink = new(queue, new MxAccessEventMapper());
MXSTATUS_PROXY[] statuses = Array.Empty<MXSTATUS_PROXY>();
DateTime local = new(2026, 3, 26, 13, 38, 22, 907, DateTimeKind.Local);
string timestampText = local.ToString(System.Globalization.CultureInfo.CurrentCulture);
// Raw MXAccess data-type code 1 == Boolean.
sink.OnBufferedDataChange(
hLMXServerHandle: 5,
phItemHandle: 13,
dtDataType: (ComMxDataType)1,
pvItemValue: new object[] { true, "not-a-bool" },
pwItemQuality: new object[] { 192, 192 },
pftItemTimeStamp: new object[] { timestampText, timestampText },
ref statuses);
Assert.False(queue.IsFaulted);
Assert.True(queue.TryDequeue(out WorkerEvent? workerEvent));
MxEvent mxEvent = workerEvent!.Event;
Assert.Equal(MxArray.ValuesOneofCase.TimestampValues, mxEvent.OnBufferedDataChange.TimestampValues.ValuesCase);
Assert.Equal(2, mxEvent.OnBufferedDataChange.TimestampValues.TimestampValues.Values.Count);
Assert.Equal(MxArray.ValuesOneofCase.RawValues, mxEvent.Value.ArrayValue.ValuesCase);
Assert.Contains("element 1", mxEvent.Value.ArrayValue.RawDiagnostic);
}
}
@@ -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)
@@ -2,13 +2,18 @@ using System;
using System.Globalization;
using System.Linq;
using Google.Protobuf;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Worker.MxAccess;
namespace ZB.MOM.WW.MxGateway.Worker.Conversion;
public sealed class VariantConverter
{
private const string FileTimeOutOfRangeDiagnostic =
"Value is outside the FILETIME range; projected as an integer.";
private readonly TimeZoneInfo? mxAccessLocalTimeZone;
/// <summary>
@@ -99,48 +104,154 @@ public sealed class VariantConverter
System.Type? elementType = array.GetType().GetElementType();
MxDataType elementDataType = ResolveArrayElementDataType(elementType, expectedElementDataType);
mxArray.ElementDataType = elementDataType;
if (TryProjectTypedArray(mxArray, array, elementDataType, elementType, out string? failure))
{
return mxArray;
}
// A typed projection failed on one element (an expected-type hint the
// element does not fit, a FILETIME out of range, an integer too wide).
// Conversion must stay total: it runs on the MXAccess event path, where
// a throw faults the whole session (WIP-003). Fall back to the
// projection the array's own CLR element type gives, and failing that
// to the raw projection with a diagnostic naming the element.
MxDataType actualDataType = ResolveArrayElementDataType(elementType, MxDataType.Unspecified);
if (failure is not null
&& actualDataType != elementDataType
&& actualDataType != MxDataType.Unknown
&& TryProjectTypedArray(mxArray, array, actualDataType, elementType, out _))
{
mxArray.RawDiagnostic = $"{failure} Projected as {actualDataType} from the array's element type.";
return mxArray;
}
mxArray.ElementDataType = MxDataType.Unknown;
mxArray.RawElementDataType = (int)expectedElementDataType;
mxArray.RawDiagnostic = failure ?? CreateRawDiagnostic(array);
mxArray.RawValues = ConvertRawArray(array);
return mxArray;
}
/// <summary>
/// Projects <paramref name="array"/> into the typed value list for
/// <paramref name="elementDataType"/>. Nothing is written to
/// <paramref name="mxArray"/> unless every element converts.
/// </summary>
/// <param name="mxArray">Array message to fill on success.</param>
/// <param name="array">Source array.</param>
/// <param name="elementDataType">Element type to project to.</param>
/// <param name="elementType">CLR element type of the source array.</param>
/// <param name="failure">
/// Why an element did not convert, or <see langword="null"/> when the data
/// type has no typed projection at all.
/// </param>
/// <returns><see langword="true"/> when the typed projection was applied.</returns>
private static bool TryProjectTypedArray(
MxArray mxArray,
Array array,
MxDataType elementDataType,
System.Type? elementType,
out string? failure)
{
switch (elementDataType)
{
case MxDataType.Boolean:
mxArray.BoolValues = ConvertBoolArray(array);
return mxArray;
{
BoolArray values = new();
if (!TryConvertElements(array, values.Values, ConvertBoolElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.BoolValues = values;
return true;
}
case MxDataType.Integer:
if (elementType == typeof(long) || elementType == typeof(ulong))
{
// Widen the same way the scalar path does (WIP-004): uint, long
// and ulong never fit an int, and an object[] (SAFEARRAY of
// VARIANT) may hold any of them, so a narrow projection that
// overflows retries as 64-bit. A ulong above long.MaxValue
// fails both and lands on the raw projection, as the scalar does.
if (!UsesInt64Projection(elementType))
{
mxArray.Int64Values = ConvertInt64Array(array);
}
else
{
mxArray.Int32Values = ConvertInt32Array(array);
Int32Array narrow = new();
if (TryConvertElements(array, narrow.Values, ConvertInt32Element, elementDataType, out failure))
{
mxArray.ElementDataType = elementDataType;
mxArray.Int32Values = narrow;
return true;
}
}
return mxArray;
Int64Array wide = new();
if (!TryConvertElements(array, wide.Values, ConvertInt64Element, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.Int64Values = wide;
return true;
}
case MxDataType.Float:
mxArray.FloatValues = ConvertFloatArray(array);
return mxArray;
{
FloatArray values = new();
if (!TryConvertElements(array, values.Values, ConvertFloatElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.FloatValues = values;
return true;
}
case MxDataType.Double:
mxArray.DoubleValues = ConvertDoubleArray(array);
return mxArray;
{
DoubleArray values = new();
if (!TryConvertElements(array, values.Values, ConvertDoubleElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.DoubleValues = values;
return true;
}
case MxDataType.String:
mxArray.StringValues = ConvertStringArray(array);
return mxArray;
{
StringArray values = new();
if (!TryConvertElements(array, values.Values, ConvertStringElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.StringValues = values;
return true;
}
case MxDataType.Time:
mxArray.TimestampValues = ConvertTimestampArray(array);
return mxArray;
{
TimestampArray values = new();
if (!TryConvertElements(array, values.Values, ConvertTimestampElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.TimestampValues = values;
return true;
}
default:
mxArray.ElementDataType = MxDataType.Unknown;
mxArray.RawElementDataType = (int)expectedElementDataType;
mxArray.RawDiagnostic = CreateRawDiagnostic(array);
mxArray.RawValues = ConvertRawArray(array);
return mxArray;
failure = null;
return false;
}
}
@@ -175,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)),
};
}
@@ -257,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)),
};
}
@@ -360,22 +471,35 @@ public sealed class VariantConverter
// 32 bits, which DateTime.FromFileTimeUtc would silently render as a
// timestamp near the 1601 epoch. For uint sources fall through to the integer
// projection rather than producing a bogus timestamp.
string? diagnostic = null;
if (expectedDataType == MxDataType.Time && value is long)
{
return new MxValue
Timestamp? timestamp = TryFromFileTimeUtc(longValue);
if (timestamp is not null)
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = Timestamp.FromDateTime(DateTime.FromFileTimeUtc(longValue)),
};
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = timestamp,
};
}
diagnostic = FileTimeOutOfRangeDiagnostic;
}
return new MxValue
MxValue converted = new()
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int64Value = longValue,
};
if (diagnostic is not null)
{
converted.RawDiagnostic = diagnostic;
}
return converted;
}
private static MxValue ConvertUInt64Scalar(
@@ -383,24 +507,37 @@ public sealed class VariantConverter
string variantType,
MxDataType expectedDataType)
{
string? diagnostic = null;
if (expectedDataType == MxDataType.Time && value <= long.MaxValue)
{
return new MxValue
Timestamp? timestamp = TryFromFileTimeUtc((long)value);
if (timestamp is not null)
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = Timestamp.FromDateTime(DateTime.FromFileTimeUtc((long)value)),
};
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = timestamp,
};
}
diagnostic = FileTimeOutOfRangeDiagnostic;
}
if (value <= long.MaxValue)
{
return new MxValue
MxValue converted = new()
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int64Value = (long)value,
};
if (diagnostic is not null)
{
converted.RawDiagnostic = diagnostic;
}
return converted;
}
return CreateRawValue(value, expectedDataType, "UInt64 value exceeds Int64 range.");
@@ -439,93 +576,134 @@ public sealed class VariantConverter
};
}
private static BoolArray ConvertBoolArray(Array array)
private static bool TryConvertElements<T>(
Array array,
RepeatedField<T> target,
Func<object?, T> convert,
MxDataType elementDataType,
out string? failure)
{
BoolArray values = new();
int index = 0;
foreach (object? item in array)
{
values.Values.Add(item is not null && System.Convert.ToBoolean(item, CultureInfo.InvariantCulture));
}
return values;
}
private static Int32Array ConvertInt32Array(Array array)
{
Int32Array values = new();
foreach (object? item in array)
{
values.Values.Add(item is null ? 0 : System.Convert.ToInt32(item, CultureInfo.InvariantCulture));
}
return values;
}
private static Int64Array ConvertInt64Array(Array array)
{
Int64Array values = new();
foreach (object? item in array)
{
values.Values.Add(item is null ? 0 : System.Convert.ToInt64(item, CultureInfo.InvariantCulture));
}
return values;
}
private static FloatArray ConvertFloatArray(Array array)
{
FloatArray values = new();
foreach (object? item in array)
{
values.Values.Add(item is null ? 0 : System.Convert.ToSingle(item, CultureInfo.InvariantCulture));
}
return values;
}
private static DoubleArray ConvertDoubleArray(Array array)
{
DoubleArray values = new();
foreach (object? item in array)
{
values.Values.Add(item is null ? 0 : System.Convert.ToDouble(item, CultureInfo.InvariantCulture));
}
return values;
}
private static StringArray ConvertStringArray(Array array)
{
StringArray values = new();
foreach (object? item in array)
{
values.Values.Add(item is null ? string.Empty : System.Convert.ToString(item, CultureInfo.InvariantCulture) ?? string.Empty);
}
return values;
}
private static TimestampArray ConvertTimestampArray(Array array)
{
TimestampArray values = new();
foreach (object? item in array)
{
if (item is null)
try
{
values.Values.Add(Timestamp.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)));
target.Add(convert(item));
}
else if (item is DateTime dateTime)
catch (Exception exception) when (IsElementConversionFailure(exception))
{
values.Values.Add(ToTimestamp(dateTime));
}
else
{
long fileTime = System.Convert.ToInt64(item, CultureInfo.InvariantCulture);
values.Values.Add(Timestamp.FromDateTime(DateTime.FromFileTimeUtc(fileTime)));
// Name the element and its CLR type, never its value: values
// are not logged by default and this text reaches the client.
failure = $"Array element {index} ({item?.GetType().FullName ?? "null"}) "
+ $"could not be projected to {elementDataType}: {exception.GetType().Name}.";
return false;
}
index++;
}
return values;
failure = null;
return true;
}
private static bool IsElementConversionFailure(Exception exception)
{
return exception is FormatException
|| exception is InvalidCastException
|| exception is OverflowException
|| exception is ArgumentException;
}
private static bool UsesInt64Projection(System.Type? elementType)
{
return elementType == typeof(uint)
|| elementType == typeof(long)
|| elementType == typeof(ulong);
}
// Null elements keep their historical default projection until a live
// capture shows how MXAccess represents a missing array element (WIP-008,
// decision D8: no invented null encoding).
private static bool ConvertBoolElement(object? item)
{
return item is not null && System.Convert.ToBoolean(item, CultureInfo.InvariantCulture);
}
private static int ConvertInt32Element(object? item)
{
return item is null ? 0 : System.Convert.ToInt32(item, CultureInfo.InvariantCulture);
}
private static long ConvertInt64Element(object? item)
{
return item is null ? 0 : System.Convert.ToInt64(item, CultureInfo.InvariantCulture);
}
private static float ConvertFloatElement(object? item)
{
return item is null ? 0 : System.Convert.ToSingle(item, CultureInfo.InvariantCulture);
}
private static double ConvertDoubleElement(object? item)
{
return item is null ? 0 : System.Convert.ToDouble(item, CultureInfo.InvariantCulture);
}
private static string ConvertStringElement(object? item)
{
return item is null ? string.Empty : System.Convert.ToString(item, CultureInfo.InvariantCulture) ?? string.Empty;
}
/// <summary>
/// Converts one element of a Time-typed array. A <c>VT_DATE</c> element is
/// a <see cref="DateTime"/>; a 64-bit integer is a FILETIME; a string is
/// the culture-formatted local time MXAccess uses for the
/// <c>OnDataChange</c> timestamp. Anything else (a 32-bit integer, which
/// can only hold the low half of a FILETIME, or a double) is rejected so the
/// caller falls back instead of emitting a timestamp near 1601.
/// </summary>
private static Timestamp ConvertTimestampElement(object? item)
{
switch (item)
{
case null:
return Timestamp.FromDateTime(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
case DateTime dateTime:
return ToTimestamp(dateTime);
case string text:
if (MxAccessEventMapper.TryParseSourceTimestamp(text, out DateTime parsedUtc))
{
return Timestamp.FromDateTime(parsedUtc);
}
throw new FormatException("Timestamp string did not parse.");
case long fileTime:
return Timestamp.FromDateTime(DateTime.FromFileTimeUtc(fileTime));
case ulong fileTime when fileTime <= long.MaxValue:
return Timestamp.FromDateTime(DateTime.FromFileTimeUtc((long)fileTime));
default:
throw new InvalidCastException("Element type has no timestamp projection.");
}
}
private static Timestamp? TryFromFileTimeUtc(long fileTime)
{
// DateTime.FromFileTimeUtc rejects negative values and values past
// DateTime.MaxValue; on the event path that throw would fault the
// session (WIP-003), so an out-of-range FILETIME stays an integer.
try
{
return Timestamp.FromDateTime(DateTime.FromFileTimeUtc(fileTime));
}
catch (ArgumentOutOfRangeException)
{
return null;
}
}
private static RawArray ConvertRawArray(Array 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)
{
}
}
@@ -11,6 +11,7 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion
private readonly MxAccessEventQueue eventQueue;
private readonly MxAccessValueCache valueCache;
private readonly MxAccessWriteCompletionCache writeCompletionCache;
private MxAccessHandleRegistry? handleRegistry;
private LMXProxyServerClass? server;
private string sessionId = string.Empty;
@@ -88,6 +89,24 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion
/// <inheritdoc />
public MxAccessWriteCompletionCache WriteCompletionCache => writeCompletionCache;
/// <summary>
/// Binds the session's handle registry so the per-handle caches only
/// record callbacks for item handles the session still holds. MXAccess
/// can dispatch an <c>OnDataChange</c> or <c>OnWriteComplete</c> that
/// was already queued on the STA after <c>RemoveItem</c> evicted the
/// handle; without this check the callback re-creates the entry, and
/// because MXAccess never reuses an item handle within a registration,
/// nothing evicts it again before <c>Unregister</c> (MXA-004). The event
/// itself is still forwarded: the gateway relays every event MXAccess
/// raises. Registry and callbacks are both STA-only, so no lock is
/// needed. An unbound sink (unit tests) caches every callback.
/// </summary>
/// <param name="registry">The owning session's handle registry.</param>
internal void BindHandleRegistry(MxAccessHandleRegistry registry)
{
handleRegistry = registry ?? throw new ArgumentNullException(nameof(registry));
}
/// <inheritdoc />
public void Attach(
object mxAccessComObject,
@@ -153,7 +172,13 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion
pwItemQuality,
pftItemTimeStamp,
statuses),
mxEvent => valueCache.Set(hLMXServerHandle, phItemHandle, mxEvent));
mxEvent =>
{
if (IsLiveItemHandle(hLMXServerHandle, phItemHandle))
{
valueCache.Set(hLMXServerHandle, phItemHandle, mxEvent);
}
});
}
/// <summary>
@@ -180,7 +205,13 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion
hLMXServerHandle,
phItemHandle,
statuses),
mxEvent => writeCompletionCache.Record(hLMXServerHandle, phItemHandle, mxEvent.Statuses));
mxEvent =>
{
if (IsLiveItemHandle(hLMXServerHandle, phItemHandle))
{
writeCompletionCache.Record(hLMXServerHandle, phItemHandle, mxEvent.Statuses);
}
});
}
/// <summary>
@@ -235,6 +266,14 @@ public sealed class MxAccessBaseEventSink : IMxAccessEventSink, IWriteCompletion
statuses));
}
private bool IsLiveItemHandle(
int serverHandle,
int itemHandle)
{
MxAccessHandleRegistry? registry = handleRegistry;
return registry is null || registry.ContainsItemHandle(serverHandle, itemHandle);
}
private void EnqueueEvent(Func<Proto.MxEvent> createEvent)
{
EnqueueEvent(createEvent, postPublish: null);
@@ -159,9 +159,19 @@ public sealed class MxAccessSession : IDisposable
// ReadBulk reads both see the same instance. Fall back to a fresh
// cache for test fakes that supply their own sink — ReadBulk simply
// never serves cached values in that case.
MxAccessValueCache valueCache = eventSink is MxAccessBaseEventSink baseSink
? baseSink.ValueCache
: new MxAccessValueCache();
MxAccessHandleRegistry handleRegistry = new();
MxAccessValueCache valueCache;
if (eventSink is MxAccessBaseEventSink baseSink)
{
valueCache = baseSink.ValueCache;
// Late callbacks for removed handles must not re-create cache
// entries nothing would ever evict (MXA-004).
baseSink.BindHandleRegistry(handleRegistry);
}
else
{
valueCache = new MxAccessValueCache();
}
// Share the sink's completion cache the same way (the production
// sink and completion-aware test sinks implement the provider
@@ -176,7 +186,7 @@ public sealed class MxAccessSession : IDisposable
mxAccessComObject,
new MxAccessComServer(mxAccessComObject),
eventSink,
new MxAccessHandleRegistry(),
handleRegistry,
valueCache,
writeCompletionCache,
Environment.CurrentManagedThreadId);
@@ -286,7 +296,9 @@ public sealed class MxAccessSession : IDisposable
/// reused id would let ReadBulk's cached fast path serve that stale
/// value as <c>was_cached = true</c>. A handle the registry still
/// tracks is a live item (MXAccess returned an existing handle), so its
/// current entries are kept.
/// current entries are kept. The production sink now skips cache
/// writes for handles the registry no longer holds (MXA-004), so this
/// is the backstop for sinks that are not bound to the registry.
/// </summary>
private void EvictStaleHandleState(
int serverHandle,
@@ -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;