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;
///
/// Initializes a converter that renders timestamped-write time arguments in
/// the worker box's local zone ().
///
public VariantConverter()
: this(mxAccessLocalTimeZone: null)
{
}
///
/// Initializes a converter with an explicit zone for the timestamped-write
/// time argument. Tests inject a fixed zone so they do not depend on the
/// zone of the machine that runs them.
///
///
/// Zone MXAccess reads the Write2/WriteSecured2 time argument in,
/// or for resolved per call.
///
public VariantConverter(TimeZoneInfo? mxAccessLocalTimeZone)
{
this.mxAccessLocalTimeZone = mxAccessLocalTimeZone;
}
///
/// Converts an object value to an MxValue without a specified data type.
///
/// Value to convert.
/// Converted MxValue.
public MxValue Convert(object? value)
{
return Convert(value, MxDataType.Unspecified);
}
///
/// Converts an object value to an MxValue with an expected data type.
///
/// Value to convert.
/// Expected MXAccess data type.
/// Converted MxValue.
public MxValue Convert(
object? value,
MxDataType expectedDataType)
{
if (value is null || value is DBNull)
{
return CreateNullValue(value, expectedDataType);
}
if (value is Array array)
{
return new MxValue
{
DataType = MxDataType.Unspecified,
VariantType = CreateArrayVariantType(array),
ArrayValue = ConvertArray(array, expectedDataType),
};
}
return ConvertScalar(value, expectedDataType);
}
///
/// Converts a .NET array to an MxArray.
///
/// Array to convert.
/// Expected data type for array elements.
/// Converted MxArray.
public MxArray ConvertArray(
Array array,
MxDataType expectedElementDataType = MxDataType.Unspecified)
{
if (array is null)
{
throw new ArgumentNullException(nameof(array));
}
MxArray mxArray = new()
{
VariantType = CreateArrayVariantType(array),
};
for (int dimension = 0; dimension < array.Rank; dimension++)
{
mxArray.Dimensions.Add((uint)array.GetLength(dimension));
}
System.Type? elementType = array.GetType().GetElementType();
MxDataType elementDataType = ResolveArrayElementDataType(elementType, expectedElementDataType);
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;
}
///
/// Projects into the typed value list for
/// . Nothing is written to
/// unless every element converts.
///
/// Array message to fill on success.
/// Source array.
/// Element type to project to.
/// CLR element type of the source array.
///
/// Why an element did not convert, or when the data
/// type has no typed projection at all.
///
/// when the typed projection was applied.
private static bool TryProjectTypedArray(
MxArray mxArray,
Array array,
MxDataType elementDataType,
System.Type? elementType,
out string? failure)
{
switch (elementDataType)
{
case MxDataType.Boolean:
{
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:
{
// 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))
{
Int32Array narrow = new();
if (TryConvertElements(array, narrow.Values, ConvertInt32Element, elementDataType, out failure))
{
mxArray.ElementDataType = elementDataType;
mxArray.Int32Values = narrow;
return true;
}
}
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:
{
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:
{
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:
{
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:
{
TimestampArray values = new();
if (!TryConvertElements(array, values.Values, ConvertTimestampElement, elementDataType, out failure))
{
return false;
}
mxArray.ElementDataType = elementDataType;
mxArray.TimestampValues = values;
return true;
}
default:
failure = null;
return false;
}
}
///
/// Converts an into a CLR object suitable for an
/// MXAccess COM write. The COM marshaler boxes the returned value into the
/// matching VARIANT, so this is the inverse of .
///
/// Protobuf value to convert.
/// A COM-marshalable value, or for an MXAccess null.
public object? ConvertToComValue(MxValue value)
{
if (value is null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.IsNull)
{
return null;
}
return value.KindCase switch
{
MxValue.KindOneofCase.BoolValue => value.BoolValue,
MxValue.KindOneofCase.Int32Value => value.Int32Value,
MxValue.KindOneofCase.Int64Value => value.Int64Value,
MxValue.KindOneofCase.FloatValue => value.FloatValue,
MxValue.KindOneofCase.DoubleValue => value.DoubleValue,
MxValue.KindOneofCase.StringValue => value.StringValue,
// The COM marshaler renders a DateTime as VT_DATE; MXAccess accepts
// it as the timestamped-write time argument.
MxValue.KindOneofCase.TimestampValue => value.TimestampValue.ToDateTime(),
MxValue.KindOneofCase.ArrayValue => ConvertToComArray(value.ArrayValue),
MxValue.KindOneofCase.RawValue => throw new WorkerRequestValidationException(
"MxValue raw payloads cannot be written to MXAccess.", nameof(value)),
_ => throw new WorkerRequestValidationException(
"MxValue has no value kind set; nothing to write.", nameof(value)),
};
}
///
/// Converts the time argument of a timestamped write (Write2,
/// WriteSecured2 and their bulk forms) into the CLR object MXAccess
/// expects. Unlike , a
/// timestamp_value instant is rendered as box-local wall-clock time.
///
///
///
/// MXAccess reads the VT_DATE time argument as local time on the worker
/// box and converts it to UTC itself, while a VT_DATE carries no
/// offset and the COM marshaler ignores . Passing
/// the UTC clock fields therefore stored the source timestamp shifted by the
/// box's UTC offset (+5 h on a UTC-5 box, #228). The read direction is the
/// opposite and stays as it is: MXAccess hands OnDataChange timestamps over
/// as UTC, and ToTimestamp treats them as UTC.
///
///
/// The UTC-to-local step uses
/// with the zone's DST rules, so it is exact and never yields an invalid
/// local time. The one residual loss is on the MXAccess side: in the hour
/// that repeats when DST ends, two UTC instants 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. Clients that
/// need exact timestamps across the fall-back hour should run the worker
/// box on UTC.
///
///
/// Only the timestamp_value kind is converted. Any other kind (a
/// string or a number) carries no zone, so it is passed through unchanged
/// as before and its meaning is the caller's.
///
///
/// Protobuf time argument of a timestamped write.
/// A COM-marshalable value for the MXAccess time argument.
public object? ConvertToComTimestamp(MxValue timestamp)
{
if (timestamp is null)
{
throw new ArgumentNullException(nameof(timestamp));
}
if (!timestamp.IsNull && timestamp.KindCase == MxValue.KindOneofCase.TimestampValue)
{
return ToMxAccessLocalTime(timestamp.TimestampValue.ToDateTime());
}
return ConvertToComValue(timestamp);
}
///
/// Converts a UTC instant to the wall-clock time MXAccess expects for a
/// timestamped-write time argument. See .
///
/// UTC instant ( or unspecified).
/// The same instant as wall-clock time in the MXAccess zone.
public DateTime ToMxAccessLocalTime(DateTime utcDateTime)
{
DateTime utc = utcDateTime.Kind == DateTimeKind.Local
? utcDateTime.ToUniversalTime()
: DateTime.SpecifyKind(utcDateTime, DateTimeKind.Utc);
return TimeZoneInfo.ConvertTimeFromUtc(utc, mxAccessLocalTimeZone ?? TimeZoneInfo.Local);
}
private static Array ConvertToComArray(MxArray array)
{
return array.ValuesCase switch
{
MxArray.ValuesOneofCase.BoolValues => array.BoolValues.Values.ToArray(),
MxArray.ValuesOneofCase.Int32Values => array.Int32Values.Values.ToArray(),
MxArray.ValuesOneofCase.Int64Values => array.Int64Values.Values.ToArray(),
MxArray.ValuesOneofCase.FloatValues => array.FloatValues.Values.ToArray(),
MxArray.ValuesOneofCase.DoubleValues => array.DoubleValues.Values.ToArray(),
MxArray.ValuesOneofCase.StringValues => array.StringValues.Values.ToArray(),
MxArray.ValuesOneofCase.TimestampValues =>
array.TimestampValues.Values.Select(timestamp => timestamp.ToDateTime()).ToArray(),
MxArray.ValuesOneofCase.RawValues => throw new WorkerRequestValidationException(
"MxArray raw payloads cannot be written to MXAccess.", nameof(array)),
_ => throw new WorkerRequestValidationException(
"MxArray has no element values set; nothing to write.", nameof(array)),
};
}
private static MxValue ConvertScalar(
object value,
MxDataType expectedDataType)
{
System.Type valueType = value.GetType();
string variantType = GetVariantTypeName(valueType);
switch (System.Type.GetTypeCode(valueType))
{
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),
};
case TypeCode.UInt32:
case TypeCode.Int64:
return ConvertInt64Scalar(value, variantType, expectedDataType);
case TypeCode.UInt64:
return ConvertUInt64Scalar((ulong)value, variantType, expectedDataType);
case TypeCode.Single:
return new MxValue
{
DataType = MxDataType.Float,
VariantType = variantType,
FloatValue = (float)value,
};
case TypeCode.Double:
return new MxValue
{
DataType = MxDataType.Double,
VariantType = variantType,
DoubleValue = (double)value,
};
case TypeCode.Decimal:
return new MxValue
{
DataType = MxDataType.Double,
VariantType = variantType,
DoubleValue = System.Convert.ToDouble(value, CultureInfo.InvariantCulture),
RawDiagnostic = "Decimal value projected to double.",
};
case TypeCode.String:
case TypeCode.Char:
return new MxValue
{
DataType = MxDataType.String,
VariantType = variantType,
StringValue = System.Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty,
};
case TypeCode.DateTime:
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = ToTimestamp((DateTime)value),
};
default:
return CreateRawValue(value, expectedDataType);
}
}
private static MxValue ConvertInt64Scalar(
object value,
string variantType,
MxDataType expectedDataType)
{
long longValue = System.Convert.ToInt64(value, CultureInfo.InvariantCulture);
// The MxDataType.Time projection treats the source as a Windows FILETIME
// (a 64-bit 100-ns tick count since 1601). Only a genuine 64-bit source
// (long) can carry a valid full FILETIME; a uint can only hold the low
// 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)
{
Timestamp? timestamp = TryFromFileTimeUtc(longValue);
if (timestamp is not null)
{
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = timestamp,
};
}
diagnostic = FileTimeOutOfRangeDiagnostic;
}
MxValue converted = new()
{
DataType = MxDataType.Integer,
VariantType = variantType,
Int64Value = longValue,
};
if (diagnostic is not null)
{
converted.RawDiagnostic = diagnostic;
}
return converted;
}
private static MxValue ConvertUInt64Scalar(
ulong value,
string variantType,
MxDataType expectedDataType)
{
string? diagnostic = null;
if (expectedDataType == MxDataType.Time && value <= long.MaxValue)
{
Timestamp? timestamp = TryFromFileTimeUtc((long)value);
if (timestamp is not null)
{
return new MxValue
{
DataType = MxDataType.Time,
VariantType = variantType,
TimestampValue = timestamp,
};
}
diagnostic = FileTimeOutOfRangeDiagnostic;
}
if (value <= long.MaxValue)
{
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.");
}
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,
};
}
private static MxValue CreateRawValue(
object value,
MxDataType expectedDataType,
string? diagnosticPrefix = null)
{
string diagnostic = CreateRawDiagnostic(value);
if (!string.IsNullOrWhiteSpace(diagnosticPrefix))
{
diagnostic = $"{diagnosticPrefix} {diagnostic}";
}
return new MxValue
{
DataType = MxDataType.Unknown,
VariantType = GetVariantTypeName(value.GetType()),
RawDataType = (int)expectedDataType,
RawDiagnostic = diagnostic,
RawValue = ByteString.CopyFromUtf8(System.Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty),
};
}
private static bool TryConvertElements(
Array array,
RepeatedField target,
Func