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.
20 KiB
Worker Conversion Layer
The conversion layer in ZB.MOM.WW.MxGateway.Worker.Conversion projects COM VARIANT payloads, HRESULT codes, and MXSTATUS_PROXY records into the protobuf wire types in ZB.MOM.WW.MxGateway.Contracts.Proto. The design is parity-first: every projection preserves enough raw metadata that the original COM observation can be reconstructed downstream.
Overview
gateway.md (sections "Value Model" and "Status Model") requires that the wire format use a value union capable of representing COM VARIANT values and arrays, that lossy conversions retain both the typed projection and raw diagnostic metadata, and that MXSTATUS_PROXY arrays never collapse to a single success flag. The types in src/ZB.MOM.WW.MxGateway.Worker/Conversion/ are the worker-side enforcement of those rules.
The layer is split into three concerns:
- Value projection:
VariantConverter - HRESULT projection:
HResultConverter,HResultConversion - Status projection:
MxStatusProxyConverter,MxStatusDetailText,MxStatusConversionException
VariantConverter
VariantConverter projects scalar and array VARIANT payloads delivered by COM interop into MxValue and MxArray. It accepts an optional expectedDataType so that an MXAccess attribute hint (for example MxDataType.Time for a 64-bit FILETIME) overrides the default CLR-driven projection.
Scalar projection
Scalars dispatch on Type.GetTypeCode and populate the matching field in the MxValue oneof. Each branch records both the typed value and the source VARIANT tag in VariantType, so consumers can distinguish a short from an int even after both project to MxDataType.Integer.
case TypeCode.Boolean:
return new MxValue
{
DataType = MxDataType.Boolean,
VariantType = variantType,
BoolValue = (bool)value,
};
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
return new MxValue
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int32Value = System.Convert.ToInt32(value, CultureInfo.InvariantCulture),
};
Decimal and 64-bit unsigned integers that exceed long.MaxValue cannot project losslessly. The converter still emits a typed best-effort value but attaches a RawDiagnostic so the loss is recorded on the wire rather than silently absorbed.
case TypeCode.Decimal:
return new MxValue
{
DataType = MxDataType.Double,
VariantType = variantType,
DoubleValue = System.Convert.ToDouble(value, CultureInfo.InvariantCulture),
RawDiagnostic = "Decimal value projected to double.",
};
Time-typed integers use the expectedDataType hint. ConvertInt64Scalar interprets a long as a Windows FILETIME when the caller asks for MxDataType.Time, otherwise it stays an integer. ConvertUInt64Scalar falls through to a raw projection if the value exceeds long.MaxValue.
Null and missing values
VARIANT distinguishes VT_EMPTY from VT_NULL. The converter preserves both by inspecting whether the input is DBNull or a CLR null reference, and tags the result with IsNull = true so consumers do not misread a default value as data.
private static MxValue CreateNullValue(
object? value,
MxDataType expectedDataType)
{
return new MxValue
{
DataType = expectedDataType == MxDataType.Unspecified ? MxDataType.NoData : expectedDataType,
VariantType = value is DBNull ? "VT_NULL" : "VT_EMPTY",
IsNull = true,
};
}
Sparse array expansion (write path, gateway only)
MxSparseArray — the sparse_array_value arm on MxValue — is a write-only
shorthand. The worker never produces or receives it; the gateway expands it into
a full MxArray before the command reaches the named pipe. Expansion allocates
a complete array of total_length slots, initializes every slot to the element
type's default (bool → false; numeric → 0; string → ""; time/timestamp →
Unix epoch), then writes each MxSparseElement at its declared index. The
resulting array_value is an ordinary MxArray that passes through the
conversion layer unchanged. The worker therefore still performs a single
whole-array COM write, preserving MXAccess parity. Unmentioned indices are
reset to their type default, not preserved from prior state — there is no
read-modify-write merge.
Array projection
ConvertArray records the rank and per-dimension lengths so multi-dimensional SAFEARRAY shapes survive the round trip. The element type is resolved from the caller-supplied hint or the CLR element type via ResolveArrayElementDataType, then TryProjectTypedArray fills the matching typed list. Nothing is written to the MxArray until every element has converted.
Conversion is total: it never throws for an element it cannot project. It runs on the MXAccess event path, where an exception is recorded as MxaccessEventConversionFailed and faults the whole session, so one bad sample in a buffered event would otherwise drop every subscription on the session. When an element does not fit the attempted type, ConvertArray falls back in this order:
- The projection the array's own CLR element type gives, when that differs from the hint. A
long[]with aTimehint and an out-of-range FILETIME becomes anInt64Valuesarray.RawDiagnosticnames the element index and CLR type that failed, never its value. - The raw projection:
ElementDataType = Unknown,RawElementDataTypeset to the original hint, each element serialized as a UTF-8 byte string byConvertRawArray, and the same element diagnostic. Anobject[](aSAFEARRAYofVARIANT) has no typed fallback and goes straight here.
An element type that has no typed projection at all (ElapsedTime, Enum, an unrecognised CLR type) takes the raw projection with the generic "unsupported variant projection" diagnostic, as before.
Element rules per typed projection:
- Integer. Widened the same way as the scalar path.
uint[],long[]andulong[]always useInt64Values, so auintaboveint.MaxValueno longer overflows. Other arrays,object[]included, tryInt32Valuesfirst and retry asInt64Valueswhen an element does not fit. Aulongabovelong.MaxValuefits neither and takes the raw projection, mirroring the scalarUInt64 value exceeds Int64 rangefallback. - Time. A
DateTime(VT_DATE) element goes throughToTimestamp. Along, or aulongup tolong.MaxValue, is a FILETIME; one outside theDateTimerange fails the element. A string is parsed withMxAccessEventMapper.TryParseSourceTimestamp, the same culture-aware local-time parse used for theOnDataChangetimestamp, because MXAccess formats that timestamp as aVT_BSTRand a buffered timestamp array may arrive the same way. Any other element (a 32-bit integer, which can only hold the low half of a FILETIME, or adouble) fails the element instead of being read as a time near 1601. - Null elements (
VT_EMPTY/VT_NULL) still take the type's default (false,0,"", the Unix epoch). How MXAccess represents a missing element in a buffered array has not been captured live, and no null encoding is invented until it is (WIP-008, decision D8 in the 2026-12-02 review plan).
The scalar FILETIME projection (an Int64 or UInt64 value with a Time hint) has the same range guard: a value outside the DateTime range stays an Int64Value with a RawDiagnostic instead of throwing.
Variant type names
GetVariantTypeName maps CLR types to canonical VT_* strings (VT_BOOL, VT_I4, VT_BSTR, VT_DATE, and so on). Unmapped CLR types fall back to CLR:<FullName> so the wire format never silently invents a VT_* tag it cannot justify. Array element tags are wrapped as SAFEARRAY(<element>) by CreateArrayVariantType.
Timestamps: the two directions differ
MXAccess does not use one time convention for both directions, so the worker does not either.
- Read (OnDataChange source timestamps,
VT_DATEvalues). MXAccess hands the worker UTC clock fields.ToTimestamptreats an unspecified-kindDateTimeas UTC and converts a local-kind one withToUniversalTime. A plainWriteon vd03 (UTC-5) reports the current UTC time as its source timestamp, which confirms this. - Write time argument (
Write2,WriteSecured2,Write2Bulk,WriteSecured2Bulk). MXAccess reads theVT_DATEtime argument as box-local time and converts it to UTC itself. AVT_DATEhas no offset field, and the COM marshaler ignoresDateTime.Kind, so passing the UTC clock fields stored the source timestamp shifted by the box's UTC offset. On vd03 aWrite2sent at01:33:00Zwas stored at06:33:00Z(#228).ConvertToComTimestamptherefore converts thetimestamp_valueinstant withTimeZoneInfo.ConvertTimeFromUtcinto the worker box's zone (TimeZoneInfo.Local, DST rules included) before the COM call. The command executor uses it for the time argument only;ConvertToComValuestill renders a timestamp value as UTC, because whether aTime-typed attribute value write follows the same rule has not been proven.
UTC to local is always defined: every UTC instant has exactly one local wall-clock time, and the conversion never produces a local time that does not exist (the skipped spring-forward hour). The one loss is on the MXAccess side. In the hour that repeats when DST ends, two UTC instants an hour apart share one local wall-clock time, and the offset-less VT_DATE cannot say which one is meant, so MXAccess may store an instant from that hour 1 h off. Run the worker box on UTC if exact timestamps across the fall-back hour matter. On a UTC box the conversion is the identity, which is why #228 could not be seen there.
A time argument of another kind (a string or a number) carries no zone and is passed through unchanged; its meaning is the caller's. Consumers must send timestamp_value as a UTC instant, as the proto Timestamp already is.
Why lossless preservation matters
The MXAccess engine returns values whose semantic type only fully resolves after consulting the engine's own attribute metadata. Clients that round-trip these values through the gateway (replay, parity fixtures, diagnostics) need the original VT_* tag, the engine-declared MxDataType, and any conversion diagnostic; otherwise edge cases such as decimal-to-double rounding, ulong overflow, or an unknown SAFEARRAY element type become invisible bugs. Storing both the typed projection and the raw fields in the same MxValue/MxArray lets cross-language clients recover the original observation byte-for-byte where possible and detect lossy cases where it is not.
HResultConverter and HResultConversion
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.
Status mapping
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.
| 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:
| Field | Purpose |
|---|---|
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 |
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
MxStatusProxyConverter projects MXAccess MXSTATUS_PROXY records into the MxStatusProxy proto message. Because the COM struct is exposed via interop reflection rather than a typed binding, the converter reads the success, category, detectedBy, and detail fields by name through FieldInfo.
public MxStatusProxy Convert(object status)
{
if (status is null)
{
throw new ArgumentNullException(nameof(status));
}
Type statusType = status.GetType();
int success = ReadInt32Field(status, statusType, "success");
int rawCategory = ReadInt32Field(status, statusType, "category");
int rawDetectedBy = ReadInt32Field(status, statusType, "detectedBy");
int detail = ReadInt32Field(status, statusType, "detail");
return new MxStatusProxy
{
Success = success,
Category = MapCategory(rawCategory),
DetectedBy = MapSource(rawDetectedBy),
Detail = detail,
RawCategory = rawCategory,
RawDetectedBy = rawDetectedBy,
DiagnosticText = MxStatusDetailText.Lookup(detail),
};
}
MapCategory and MapSource translate the integer codes documented for MXSTATUS_PROXY (for example 0 = Ok, 3 = CommunicationError, 0 = RequestingLmx, 5 = RespondingAutomationObject) into typed enums. The original integers are preserved alongside the typed projection in RawCategory and RawDetectedBy, so any code the runtime emits outside the documented range is still observable.
Status arrays
ConvertMany walks an inbound Array of status structs and emits IReadOnlyList<MxStatusProxy>. Null entries become explicit Unknown/Unknown placeholders with a diagnostic text rather than being dropped, so the index of each status still aligns with the index of the value or item handle it describes.
foreach (object? status in statuses)
{
if (status is null)
{
converted.Add(new MxStatusProxy
{
Category = MxStatusCategory.Unknown,
DetectedBy = MxStatusSource.Unknown,
DiagnosticText = "Null MXSTATUS_PROXY entry.",
});
continue;
}
converted.Add(Convert(status));
}
Why arrays are not collapsed
A single MXAccess command (notably Read, Write, and event callbacks) can return one status per item handle. gateway.md requires that the wire format represent each entry independently, because collapsing them to a Boolean success flag hides partial failures: a 50-item write where one item fails would be indistinguishable from a 50-item write where every item failed. Preserving the array per-position lets clients correlate each MxStatusProxy with its item handle and MxValue.
Completion-only status fallback
When MXAccess returns a status payload that is not a recognizable MXSTATUS_PROXY struct (for example a completion-only byte buffer from older runtimes), PreserveCompletionOnlyStatusBytes hex-encodes the raw bytes so they survive transport even though they cannot be typed.
public string PreserveCompletionOnlyStatusBytes(byte[] statusBytes)
{
if (statusBytes is null)
{
throw new ArgumentNullException(nameof(statusBytes));
}
return $"completion_only_status_hex={BitConverter.ToString(statusBytes).Replace("-", string.Empty)}";
}
MxStatusDetailText
MxStatusDetailText is an internal lookup that maps known MXSTATUS_PROXY.detail codes to short human-readable strings (for example 28 = "Index out of range", 42 = "Unable to convert string", 8017 = "Object must be offscan to modify attributes that have an MxSecurityConfigure security classification"). MxStatusProxyConverter.Convert calls Lookup and writes the result to DiagnosticText. Unknown codes return string.Empty, leaving the numeric Detail field as the authoritative identifier.
The mapping covers the engine-error range documented for MXAccess (16-50, 56-61, 541-542, 8017). Adding entries here is the supported way to enrich wire-level diagnostics without changing the proto schema.
MxStatusConversionException
MxStatusConversionException is the worker-internal signal that a status struct could not be projected at all - for example, the interop type is missing one of the required fields, or the field is null. MxStatusProxyConverter.ReadInt32Field raises it with a message that names both the offending CLR type and the missing field.
private static int ReadInt32Field(
object value,
Type valueType,
string fieldName)
{
FieldInfo? field = valueType.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public);
if (field is null)
{
throw new MxStatusConversionException(
$"Status object type '{valueType.FullName}' does not expose required field '{fieldName}'.");
}
object? fieldValue = field.GetValue(value);
if (fieldValue is null)
{
throw new MxStatusConversionException(
$"Status object field '{fieldName}' on type '{valueType.FullName}' is null.");
}
return System.Convert.ToInt32(fieldValue, CultureInfo.InvariantCulture);
}
The exception is distinct from COMException so the worker's command pipeline can route it through a dedicated handler. Callers typically translate it into a ProtocolStatus with ProtocolStatusCode.MxaccessFailure and a synthetic HRESULT, then attach the exception message as a RawDiagnostic rather than letting the failure surface as a generic worker error.