fix(scripting): #1100 a script result is what an OPC UA node can carry, in both runners — Guid crosses the wire, unpublishable types are refused alike
Where an in-process result really ends up: VirtualTagActor -> VirtualTagHostActor -> OpcUaPublishActor ->
OtOpcUaNodeManager.WriteValueLocked -> SdkValueBoundary.FromClr (VariantHelper.TryCastFrom). Probed against
SDK 2.0.1: Guid / Guid[] become an OPC UA Guid scalar/array; KeyValuePair<,>[] (a returned Dictionary),
decimal, enum, TimeSpan, char, DateTimeOffset, tuples, Nullable<T>[] and rank>1 arrays are refused, so the
node write threw, OpcUaPublishActor logged a Warning, and the node kept its PREVIOUS value and status (a
silent freeze, possibly under Good) while the worker answered "unsupported type".
Decision, per type, by what a client can see:
- Guid (scalar + 1-D array): representable -> the wire gains an additive GUID tag (15, `bytes g = 10`,
16 ToByteArray bytes; a wrong length is a protocol fault). Guid INPUTS cross too. protocol_version stays 1:
the worker ships in the host's script-worker/ folder, and an unknown tag already fails closed.
- Everything FromClr refuses: refused identically in both runners by ScriptResultMaterializer, inside the run,
with one reason ("script threw: The script returned a value of type 'KeyValuePair<Int32, Double>[]', which
an OPC UA node cannot carry; return ..."). A lazy unpublishable sequence is refused before it runs.
ScriptResultMaterializer.PublishableScalarTypes / IsPublishable own the set.
Pins: SdkValueBoundaryScriptResultTests (OpcUaServer.Tests, new Core.Scripting ref) checks IsPublishable ==
"FromClr takes it" over 34 values; ProtocolTests checks the wire carries every publishable type scalar + array;
ParityTests gains guid / guid array / guid list / dictionary / KVP[] / lazy KVPs / KVP / decimal / decimal[] /
enum / TimeSpan / char[] / 2-D rows, a Guid unboxing row, and a positive+negative control. Mutations: with the
type check disabled 11 parity tests fail; with Guid not encoded 9 protocol/parity tests fail.
Behaviour change: a value script returning a Dictionary, decimal, enum, TimeSpan, char or tuple now fails
(Bad + script log) in process too, instead of "succeeding" and leaving its node frozen. Remaining divergence:
a jagged array (publish path carries it as Variant[], worker answers "unsupported type") — follow-up.
This commit is contained in:
+11
-1
@@ -268,7 +268,17 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
|
|||||||
since #1092 — it is held to the cap by its `Count`, then copied into the same typed array
|
since #1092 — it is held to the cap by its `Count`, then copied into the same typed array
|
||||||
(`double[]`, …), and refused for an open element type (`List<object>`) — because the out-of-process
|
(`double[]`, …), and refused for an open element type (`List<object>`) — because the out-of-process
|
||||||
worker's wire carries arrays but no collection type (it used to answer `unsupported type` while the
|
worker's wire carries arrays but no collection type (it used to answer `unsupported type` while the
|
||||||
in-process runner returned the list itself). Arrays, strings and scalars are unchanged. **Still in-process-only limits** (the boundary is
|
in-process runner returned the list itself). Arrays, strings and scalars are unchanged, provided their
|
||||||
|
type is one an OPC UA node can carry. **The result's type is checked too (#1100):** a value script may
|
||||||
|
return null, a `bool`, an integer type, `float`, `double`, `string`, `DateTime` or `Guid`, or a
|
||||||
|
one-dimensional array of one of them (`ScriptResultMaterializer.PublishableScalarTypes` — exactly what
|
||||||
|
the server's OPC UA value boundary turns into a built-in Variant). Anything else — a `Dictionary`
|
||||||
|
(it becomes `KeyValuePair<K,V>[]`), a `decimal`, an enum, a `TimeSpan`, a `char`, a tuple, a 2-D array —
|
||||||
|
fails the run (Bad, script log) in both runners with `script threw: The script returned a value of type
|
||||||
|
'…', which an OPC UA node cannot carry; …`. ⚠️ Behaviour change: in process such a value used to
|
||||||
|
"succeed" and then fail inside the node write, so the node silently kept its previous value and status
|
||||||
|
(only a server-log warning); convert first (`Convert.ToDouble(x)`, or a dictionary's keys and values as
|
||||||
|
two arrays). **Still in-process-only limits** (the boundary is
|
||||||
`Scripting:Runner=OutOfProcess`): memory exhaustion inside a run (the sample is after the fact), a
|
`Scripting:Runner=OutOfProcess`): memory exhaustion inside a run (the sample is after the fact), a
|
||||||
non-terminating loop (an orphan thread, then quarantine) and the same two inside an enumerated
|
non-terminating loop (an orphan thread, then quarantine) and the same two inside an enumerated
|
||||||
sequence. See `docs/VirtualTags.md` §"Known resource limits (accepted trade-offs)". The out-of-process
|
sequence. See `docs/VirtualTags.md` §"Known resource limits (accepted trade-offs)". The out-of-process
|
||||||
|
|||||||
+12
-5
File diff suppressed because one or more lines are too long
@@ -220,6 +220,7 @@ message Variant {
|
|||||||
STRING = 12;
|
STRING = 12;
|
||||||
DATETIME_UTC = 13;
|
DATETIME_UTC = 13;
|
||||||
ARRAY = 14;
|
ARRAY = 14;
|
||||||
|
GUID = 15; // lmxopcua#1100 (additive): System.Guid, carried in `g` as its 16 ToByteArray() bytes
|
||||||
}
|
}
|
||||||
TypeTag type = 1; // the exact CLR type: (short)ctx.GetTag(x).Value must keep working
|
TypeTag type = 1; // the exact CLR type: (short)ctx.GetTag(x).Value must keep working
|
||||||
oneof v {
|
oneof v {
|
||||||
@@ -231,6 +232,7 @@ message Variant {
|
|||||||
string s = 7;
|
string s = 7;
|
||||||
int64 dt_ticks = 8;
|
int64 dt_ticks = 8;
|
||||||
ArrayValue array = 9;
|
ArrayValue array = 9;
|
||||||
|
bytes g = 10; // GUID payload (exactly 16 bytes)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,12 @@ public static class VariantCodec
|
|||||||
variant.Type = Variant.Types.TypeTag.DatetimeUtc;
|
variant.Type = Variant.Types.TypeTag.DatetimeUtc;
|
||||||
variant.DtTicks = ToUtc(v).Ticks;
|
variant.DtTicks = ToUtc(v).Ticks;
|
||||||
return true;
|
return true;
|
||||||
|
case Guid v:
|
||||||
|
// lmxopcua#1100: a Guid is an OPC UA built-in (the publish path serves it as one), so it crosses the wire
|
||||||
|
// rather than failing "unsupported type" where the in-process runner gave the client a Guid.
|
||||||
|
variant.Type = Variant.Types.TypeTag.Guid;
|
||||||
|
variant.G = Google.Protobuf.ByteString.CopyFrom(v.ToByteArray());
|
||||||
|
return true;
|
||||||
case Array array when array.Rank == 1 && TryElementTag(array.GetType().GetElementType()!, out var elementTag):
|
case Array array when array.Rank == 1 && TryElementTag(array.GetType().GetElementType()!, out var elementTag):
|
||||||
{
|
{
|
||||||
var av = new ArrayValue { ElementType = elementTag };
|
var av = new ArrayValue { ElementType = elementTag };
|
||||||
@@ -94,6 +100,7 @@ public static class VariantCodec
|
|||||||
Variant.Types.TypeTag.Double => Expect(variant, Variant.VOneofCase.D).D,
|
Variant.Types.TypeTag.Double => Expect(variant, Variant.VOneofCase.D).D,
|
||||||
Variant.Types.TypeTag.String => Expect(variant, Variant.VOneofCase.S).S,
|
Variant.Types.TypeTag.String => Expect(variant, Variant.VOneofCase.S).S,
|
||||||
Variant.Types.TypeTag.DatetimeUtc => new DateTime(Expect(variant, Variant.VOneofCase.DtTicks).DtTicks, DateTimeKind.Utc),
|
Variant.Types.TypeTag.DatetimeUtc => new DateTime(Expect(variant, Variant.VOneofCase.DtTicks).DtTicks, DateTimeKind.Utc),
|
||||||
|
Variant.Types.TypeTag.Guid => DecodeGuid(Expect(variant, Variant.VOneofCase.G)),
|
||||||
Variant.Types.TypeTag.Array => DecodeArray(Expect(variant, Variant.VOneofCase.Array).Array),
|
Variant.Types.TypeTag.Array => DecodeArray(Expect(variant, Variant.VOneofCase.Array).Array),
|
||||||
_ => throw new ScriptWorkerProtocolException($"unknown variant type tag {(int)variant.Type}"),
|
_ => throw new ScriptWorkerProtocolException($"unknown variant type tag {(int)variant.Type}"),
|
||||||
};
|
};
|
||||||
@@ -117,6 +124,15 @@ public static class VariantCodec
|
|||||||
return variant;
|
return variant;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Guid DecodeGuid(Variant variant)
|
||||||
|
{
|
||||||
|
// An absent payload is the default value, as for every other tag (see Expect); a present one is exactly 16 bytes.
|
||||||
|
if (variant.VCase == Variant.VOneofCase.None || variant.G.IsEmpty) return Guid.Empty;
|
||||||
|
if (variant.G.Length != 16)
|
||||||
|
throw new ScriptWorkerProtocolException($"variant tagged {variant.Type} carries {variant.G.Length} bytes, not 16");
|
||||||
|
return new Guid(variant.G.Span);
|
||||||
|
}
|
||||||
|
|
||||||
private static Array DecodeArray(ArrayValue? array)
|
private static Array DecodeArray(ArrayValue? array)
|
||||||
{
|
{
|
||||||
if (array is null) throw new ScriptWorkerProtocolException("array variant without an array payload");
|
if (array is null) throw new ScriptWorkerProtocolException("array variant without an array payload");
|
||||||
@@ -149,6 +165,7 @@ public static class VariantCodec
|
|||||||
_ when elementType == typeof(double) => Variant.Types.TypeTag.Double,
|
_ when elementType == typeof(double) => Variant.Types.TypeTag.Double,
|
||||||
_ when elementType == typeof(string) => Variant.Types.TypeTag.String,
|
_ when elementType == typeof(string) => Variant.Types.TypeTag.String,
|
||||||
_ when elementType == typeof(DateTime) => Variant.Types.TypeTag.DatetimeUtc,
|
_ when elementType == typeof(DateTime) => Variant.Types.TypeTag.DatetimeUtc,
|
||||||
|
_ when elementType == typeof(Guid) => Variant.Types.TypeTag.Guid,
|
||||||
_ => Variant.Types.TypeTag.Null,
|
_ => Variant.Types.TypeTag.Null,
|
||||||
};
|
};
|
||||||
return tag != Variant.Types.TypeTag.Null;
|
return tag != Variant.Types.TypeTag.Null;
|
||||||
@@ -169,6 +186,7 @@ public static class VariantCodec
|
|||||||
Variant.Types.TypeTag.Double => typeof(double),
|
Variant.Types.TypeTag.Double => typeof(double),
|
||||||
Variant.Types.TypeTag.String => typeof(string),
|
Variant.Types.TypeTag.String => typeof(string),
|
||||||
Variant.Types.TypeTag.DatetimeUtc => typeof(DateTime),
|
Variant.Types.TypeTag.DatetimeUtc => typeof(DateTime),
|
||||||
|
Variant.Types.TypeTag.Guid => typeof(Guid),
|
||||||
_ => throw new ScriptWorkerProtocolException($"array element type {tag} is not supported"),
|
_ => throw new ScriptWorkerProtocolException($"array element type {tag} is not supported"),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,7 +32,15 @@ public sealed class ScriptResultException : InvalidOperationException
|
|||||||
/// (<c>object</c>, an interface, another collection) is refused — the host copies and compares returned arrays
|
/// (<c>object</c>, an interface, another collection) is refused — the host copies and compares returned arrays
|
||||||
/// recursively, so an open-slot array can nest or contain itself (see <c>ForbiddenTypeAnalyzer</c>). Arrays are
|
/// recursively, so an open-slot array can nest or contain itself (see <c>ForbiddenTypeAnalyzer</c>). Arrays are
|
||||||
/// returned as-is (fully built by the run) but are still held to the element cap. Everything else — scalars,
|
/// returned as-is (fully built by the run) but are still held to the element cap. Everything else — scalars,
|
||||||
/// strings, null — is untouched.
|
/// strings, null — is untouched, provided its type is publishable.
|
||||||
|
/// </para>
|
||||||
|
/// <para>
|
||||||
|
/// The result's TYPE is checked too (lmxopcua#1100): only what the OPC UA publish path can represent passes —
|
||||||
|
/// see <see cref="PublishableScalarTypes"/> / <see cref="IsPublishable"/>. Anything else (a
|
||||||
|
/// <c>KeyValuePair<K,V>[]</c>, which is what a returned dictionary becomes, a <c>decimal</c>, an enum, a
|
||||||
|
/// <c>TimeSpan</c>, a tuple) fails the run with a <see cref="ScriptResultException"/> in both runners. Before, the
|
||||||
|
/// in-process runner handed it on and the node write threw, leaving the node on its previous value and status
|
||||||
|
/// with only a server-log warning, while the worker answered "unsupported type".
|
||||||
/// </para>
|
/// </para>
|
||||||
/// <para>
|
/// <para>
|
||||||
/// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the
|
/// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the
|
||||||
@@ -66,6 +74,7 @@ public static class ScriptResultMaterializer
|
|||||||
case null or string:
|
case null or string:
|
||||||
return value;
|
return value;
|
||||||
case Array array:
|
case Array array:
|
||||||
|
EnsurePublishable(array.GetType());
|
||||||
EnforceCap(array.Length, maxElements);
|
EnforceCap(array.Length, maxElements);
|
||||||
return array;
|
return array;
|
||||||
case ICollection collection:
|
case ICollection collection:
|
||||||
@@ -74,10 +83,61 @@ public static class ScriptResultMaterializer
|
|||||||
case IEnumerable sequence:
|
case IEnumerable sequence:
|
||||||
return MaterializeSequence(sequence, maxElements, IsGenericCollection(sequence.GetType()) ? "collection" : "lazy sequence");
|
return MaterializeSequence(sequence, maxElements, IsGenericCollection(sequence.GetType()) ? "collection" : "lazy sequence");
|
||||||
default:
|
default:
|
||||||
|
EnsurePublishable(value.GetType());
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The scalar CLR types a script result may have, alone or as the element type of a one-dimensional array
|
||||||
|
/// (lmxopcua#1100): exactly the types the server's OPC UA value boundary (<c>SdkValueBoundary.FromClr</c>) turns
|
||||||
|
/// into a built-in Variant — Boolean, the eight integer types, Float, Double, String, DateTime and Guid — and,
|
||||||
|
/// with them, the types the out-of-process wire (<c>VariantCodec</c>) carries. Pinned against both by tests.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<Type> PublishableScalarTypes { get; } =
|
||||||
|
[
|
||||||
|
typeof(bool), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint),
|
||||||
|
typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(string), typeof(DateTime), typeof(Guid),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Whether a returned value of <paramref name="type"/> can reach an OPC UA client (lmxopcua#1100): a
|
||||||
|
/// <see cref="PublishableScalarTypes"/> scalar, or a one-dimensional array whose element type is publishable
|
||||||
|
/// (a jagged array of them included — the publish path carries it as an array of Variants).
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="type">The runtime type of the returned value.</param>
|
||||||
|
/// <returns><c>true</c> when the publish path can represent the value.</returns>
|
||||||
|
public static bool IsPublishable(Type type)
|
||||||
|
{
|
||||||
|
if (type.IsArray)
|
||||||
|
return type.GetArrayRank() == 1 && !type.IsVariableBoundArray && IsPublishable(type.GetElementType()!);
|
||||||
|
return PublishableScalarTypes.Contains(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
// lmxopcua#1100: a value the OPC UA publish path cannot represent (a KeyValuePair[] — what a returned Dictionary
|
||||||
|
// becomes — a decimal, an enum, a TimeSpan, …) used to "succeed" in process and then fail inside the node write
|
||||||
|
// (SdkValueBoundary.FromClr throws; OpcUaPublishActor logs it), so the node silently kept its previous value under its
|
||||||
|
// previous status, while the worker refused the same script "unsupported type". Refused here, inside the run, it is
|
||||||
|
// the same Bad + script-log failure in both runners.
|
||||||
|
private static void EnsurePublishable(Type type)
|
||||||
|
{
|
||||||
|
if (IsPublishable(type)) return;
|
||||||
|
throw new ScriptResultException(
|
||||||
|
$"The script returned a value of type '{Describe(type)}', which an OPC UA node cannot carry; return null, " +
|
||||||
|
"a bool, an integer type, float, double, string, DateTime or Guid, or a one-dimensional array of one of them " +
|
||||||
|
"(convert first, e.g. Convert.ToDouble(x) for a decimal, or the keys and values of a dictionary as two arrays).");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Describe(Type type)
|
||||||
|
{
|
||||||
|
if (type.IsArray) return Describe(type.GetElementType()!) + (type.GetArrayRank() == 1 ? "[]" : $"[{new string(',', type.GetArrayRank() - 1)}]");
|
||||||
|
if (!type.IsGenericType) return type.Name;
|
||||||
|
var name = type.Name;
|
||||||
|
var tick = name.IndexOf('`');
|
||||||
|
if (tick >= 0) name = name[..tick];
|
||||||
|
return $"{name}<{string.Join(", ", type.GetGenericArguments().Select(Describe))}>";
|
||||||
|
}
|
||||||
|
|
||||||
private static object MaterializeSequence(IEnumerable sequence, int maxElements, string what)
|
private static object MaterializeSequence(IEnumerable sequence, int maxElements, string what)
|
||||||
{
|
{
|
||||||
var elementType = ElementTypeOf(sequence.GetType())
|
var elementType = ElementTypeOf(sequence.GetType())
|
||||||
@@ -88,6 +148,9 @@ public static class ScriptResultMaterializer
|
|||||||
throw new ScriptResultException(
|
throw new ScriptResultException(
|
||||||
$"The script returned a {what} of '{elementType.Name}', which can contain another sequence or itself; " +
|
$"The script returned a {what} of '{elementType.Name}', which can contain another sequence or itself; " +
|
||||||
"return a typed array of a concrete type (double[], string[], …).");
|
"return a typed array of a concrete type (double[], string[], …).");
|
||||||
|
// Checked before anything is enumerated: a sequence that could only become an unpublishable array is refused
|
||||||
|
// without running it.
|
||||||
|
EnsurePublishable(elementType.MakeArrayType());
|
||||||
|
|
||||||
var items = new List<object?>();
|
var items = new List<object?>();
|
||||||
foreach (var item in sequence)
|
foreach (var item in sequence)
|
||||||
|
|||||||
@@ -79,6 +79,53 @@ public sealed class ScriptResultMaterializerTests
|
|||||||
.Message.ShouldContain("no IEnumerable<T> element type");
|
.Message.ShouldContain("no IEnumerable<T> element type");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// lmxopcua#1100: a result the OPC UA publish path cannot represent is refused inside the run. In process it used
|
||||||
|
/// to pass and then fail in the node write (the node silently kept its previous value and status).
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void A_value_no_OPC_UA_node_can_carry_is_refused()
|
||||||
|
{
|
||||||
|
object[] refused =
|
||||||
|
[
|
||||||
|
1.5m, DayOfWeek.Monday, TimeSpan.FromSeconds(1), 'a', DateTimeOffset.UnixEpoch, new KeyValuePair<int, int>(1, 2),
|
||||||
|
(1, 2), new[] { new KeyValuePair<int, int>(1, 2) }, new[] { 1.5m }, new double[1, 1], new Guid?[] { null },
|
||||||
|
new Dictionary<int, double> { [1] = 1.5 },
|
||||||
|
];
|
||||||
|
foreach (var value in refused)
|
||||||
|
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(value, 100), value.GetType().Name)
|
||||||
|
.Message.ShouldContain("which an OPC UA node cannot carry");
|
||||||
|
|
||||||
|
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new Dictionary<string, int> { ["a"] = 1 }, 100))
|
||||||
|
.Message.ShouldStartWith("The script returned a value of type 'KeyValuePair<String, Int32>[]'");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void An_unpublishable_lazy_sequence_is_refused_before_it_runs()
|
||||||
|
{
|
||||||
|
var ran = 0;
|
||||||
|
var lazy = Enumerable.Range(0, 3).Select(i => { ran++; return (decimal)i; });
|
||||||
|
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(lazy, 100));
|
||||||
|
ran.ShouldBe(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Every_publishable_type_passes_scalar_and_array_positive_controls()
|
||||||
|
{
|
||||||
|
var guid = Guid.NewGuid();
|
||||||
|
ScriptResultMaterializer.Materialize(guid, 100).ShouldBe(guid);
|
||||||
|
ScriptResultMaterializer.Materialize(new[] { guid }, 100).ShouldBeOfType<Guid[]>();
|
||||||
|
ScriptResultMaterializer.Materialize(new List<Guid> { guid }, 100).ShouldBeOfType<Guid[]>().ShouldBe([guid]);
|
||||||
|
// A jagged array is publishable too (the OPC UA boundary carries it as an array of Variants).
|
||||||
|
ScriptResultMaterializer.Materialize(new[] { new[] { 1 } }, 100).ShouldBeOfType<int[][]>();
|
||||||
|
foreach (var type in ScriptResultMaterializer.PublishableScalarTypes)
|
||||||
|
{
|
||||||
|
var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!;
|
||||||
|
ScriptResultMaterializer.Materialize(scalar, 100).ShouldBe(scalar);
|
||||||
|
ScriptResultMaterializer.Materialize(Array.CreateInstance(type, 1), 100)!.GetType().ShouldBe(type.MakeArrayType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void An_oversized_array_or_collection_is_refused_by_the_same_cap()
|
public void An_oversized_array_or_collection_is_refused_by_the_same_cap()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using Shouldly;
|
||||||
|
using Xunit;
|
||||||
|
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||||
|
|
||||||
|
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// lmxopcua#1100: the script-result rule (<see cref="ScriptResultMaterializer.IsPublishable"/>, applied by both
|
||||||
|
/// script runners) must agree with what the publish path really takes — <see cref="SdkValueBoundary.FromClr"/>, which
|
||||||
|
/// every node value write goes through. A value the rule passes but FromClr refuses is the defect #1100 found (the
|
||||||
|
/// node write threw, the node silently kept its previous value and status); a value FromClr takes but the rule refuses
|
||||||
|
/// would take a working result away from clients.
|
||||||
|
/// </summary>
|
||||||
|
[Trait("Category", "Unit")]
|
||||||
|
public sealed class SdkValueBoundaryScriptResultTests
|
||||||
|
{
|
||||||
|
public static TheoryData<string, object> Values() => new()
|
||||||
|
{
|
||||||
|
// publishable
|
||||||
|
{ "bool", true }, { "sbyte", (sbyte)1 }, { "byte", (byte)1 }, { "short", (short)1 }, { "ushort", (ushort)1 },
|
||||||
|
{ "int", 1 }, { "uint", 1u }, { "long", 1L }, { "ulong", 1UL }, { "float", 1f }, { "double", 1.0 },
|
||||||
|
{ "string", "s" }, { "DateTime", DateTime.UtcNow }, { "Guid", Guid.NewGuid() },
|
||||||
|
{ "int[]", new[] { 1 } }, { "byte[]", new byte[] { 1 } }, { "string[]", new[] { "a", null! } },
|
||||||
|
{ "DateTime[]", new[] { DateTime.UtcNow } }, { "Guid[]", new[] { Guid.NewGuid() } }, { "int[][]", new[] { new[] { 1 } } },
|
||||||
|
// not publishable
|
||||||
|
{ "decimal", 1.5m }, { "decimal[]", new[] { 1.5m } }, { "enum", DayOfWeek.Monday }, { "enum[]", new[] { DayOfWeek.Monday } },
|
||||||
|
{ "TimeSpan", TimeSpan.FromSeconds(1) }, { "char", 'a' }, { "char[]", new[] { 'a' } },
|
||||||
|
{ "DateTimeOffset", DateTimeOffset.UnixEpoch }, { "KeyValuePair", new KeyValuePair<int, int>(1, 2) },
|
||||||
|
{ "KeyValuePair[]", new[] { new KeyValuePair<int, int>(1, 2) } }, { "tuple[]", new[] { (1, 2) } },
|
||||||
|
{ "double[,]", new double[1, 1] }, { "Guid?[]", new Guid?[] { Guid.Empty } },
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(Values))]
|
||||||
|
public void The_script_result_rule_is_what_the_publish_path_takes(string name, object value)
|
||||||
|
{
|
||||||
|
var publishable = ScriptResultMaterializer.IsPublishable(value.GetType());
|
||||||
|
bool taken;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SdkValueBoundary.FromClr(value);
|
||||||
|
taken = true;
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
taken = false;
|
||||||
|
}
|
||||||
|
publishable.ShouldBe(taken, name);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Every_publishable_scalar_type_and_its_array_reach_the_publish_path()
|
||||||
|
{
|
||||||
|
foreach (var type in ScriptResultMaterializer.PublishableScalarTypes)
|
||||||
|
{
|
||||||
|
var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!;
|
||||||
|
Should.NotThrow(() => SdkValueBoundary.FromClr(scalar), type.Name);
|
||||||
|
Should.NotThrow(() => SdkValueBoundary.FromClr(Array.CreateInstance(type, 1)), type.Name + "[]");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
@@ -20,6 +20,8 @@
|
|||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\..\..\src\Server\ZB.MOM.WW.OtOpcUa.OpcUaServer\ZB.MOM.WW.OtOpcUa.OpcUaServer.csproj"/>
|
<ProjectReference Include="..\..\..\src\Server\ZB.MOM.WW.OtOpcUa.OpcUaServer\ZB.MOM.WW.OtOpcUa.OpcUaServer.csproj"/>
|
||||||
<ProjectReference Include="..\..\..\src\Core\ZB.MOM.WW.OtOpcUa.Configuration\ZB.MOM.WW.OtOpcUa.Configuration.csproj"/>
|
<ProjectReference Include="..\..\..\src\Core\ZB.MOM.WW.OtOpcUa.Configuration\ZB.MOM.WW.OtOpcUa.Configuration.csproj"/>
|
||||||
|
<!-- lmxopcua#1100: SdkValueBoundaryScriptResultTests pins ScriptResultMaterializer.IsPublishable against FromClr. -->
|
||||||
|
<ProjectReference Include="..\..\..\src\Core\ZB.MOM.WW.OtOpcUa.Core.Scripting\ZB.MOM.WW.OtOpcUa.Core.Scripting.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -421,9 +421,16 @@ public sealed class ContainmentTests
|
|||||||
public async Task Unsupported_input_and_result_types_are_explicit_failures()
|
public async Task Unsupported_input_and_result_types_are_explicit_failures()
|
||||||
{
|
{
|
||||||
await using var runner = Scripts.Runner(Scripts.Options());
|
await using var runner = Scripts.Runner(Scripts.Options());
|
||||||
var result = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair<int, int>(1, 2);"), Ct);
|
// The one result shape the materializer passes (the OPC UA publish path carries it as an array of Variants) but
|
||||||
|
// the wire does not: a jagged array. Every other unpublishable result is refused by ScriptResultMaterializer in
|
||||||
|
// both runners alike since lmxopcua#1100 ("script threw: … cannot carry …", see ParityTests).
|
||||||
|
var result = await runner.RunAsync(Scripts.Vt("jagged", "return new[] { new[] { 1 } };"), Ct);
|
||||||
result.Status.ShouldBe(ScriptRunStatus.Failed);
|
result.Status.ShouldBe(ScriptRunStatus.Failed);
|
||||||
result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Collections.Generic.KeyValuePair");
|
result.Reason!.ShouldStartWith("unsupported type: script returned a value of unsupported type System.Int32[][]");
|
||||||
|
|
||||||
|
var pair = await runner.RunAsync(Scripts.Vt("pair", "return new System.Collections.Generic.KeyValuePair<int, int>(1, 2);"), Ct);
|
||||||
|
pair.Status.ShouldBe(ScriptRunStatus.Failed);
|
||||||
|
pair.Reason!.ShouldStartWith("script threw: The script returned a value of type 'KeyValuePair<Int32, Int32>', which an OPC UA node cannot carry");
|
||||||
|
|
||||||
// lmxopcua#1092: a returned List<T> is no longer one of these — both runners copy it into a typed array first
|
// lmxopcua#1092: a returned List<T> is no longer one of these — both runners copy it into a typed array first
|
||||||
// (ScriptResultMaterializer), so it crosses the wire as int[] (this used to be the "unsupported type" example).
|
// (ScriptResultMaterializer), so it crosses the wire as int[] (this used to be the "unsupported type" example).
|
||||||
@@ -431,8 +438,11 @@ public sealed class ContainmentTests
|
|||||||
list.Status.ShouldBe(ScriptRunStatus.Ok, list.Reason);
|
list.Status.ShouldBe(ScriptRunStatus.Ok, list.Reason);
|
||||||
list.Value.ShouldBeOfType<int[]>().ShouldBe([1]);
|
list.Value.ShouldBeOfType<int[]>().ShouldBe([1]);
|
||||||
|
|
||||||
var input = await runner.RunAsync(Scripts.Vt("guid", "return 1;", inputs: Scripts.Input("g", Guid.NewGuid())), Ct);
|
// lmxopcua#1100: a Guid input crosses now (GUID tag); a decimal one still has no tag.
|
||||||
|
var guid = await runner.RunAsync(Scripts.Vt("guid", "return 1;", inputs: Scripts.Input("g", Guid.NewGuid())), Ct);
|
||||||
|
guid.Status.ShouldBe(ScriptRunStatus.Ok, guid.Reason);
|
||||||
|
var input = await runner.RunAsync(Scripts.Vt("decimal", "return 1;", inputs: Scripts.Input("d", 1.5m)), Ct);
|
||||||
input.Status.ShouldBe(ScriptRunStatus.Failed);
|
input.Status.ShouldBe(ScriptRunStatus.Failed);
|
||||||
input.Reason!.ShouldStartWith("unsupported type: input 'g' has a value of unsupported type System.Guid");
|
input.Reason!.ShouldStartWith("unsupported type: input 'd' has a value of unsupported type System.Decimal");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ public sealed class ParityTests
|
|||||||
{ "bool", true }, { "sbyte", (sbyte)-2 }, { "byte", (byte)2 }, { "short", (short)-3 }, { "ushort", (ushort)3 },
|
{ "bool", true }, { "sbyte", (sbyte)-2 }, { "byte", (byte)2 }, { "short", (short)-3 }, { "ushort", (ushort)3 },
|
||||||
{ "int", -4 }, { "uint", 4u }, { "long", -5L }, { "ulong", 5UL }, { "float", 1.25f }, { "double", 2.5 },
|
{ "int", -4 }, { "uint", 4u }, { "long", -5L }, { "ulong", 5UL }, { "float", 1.25f }, { "double", 2.5 },
|
||||||
{ "string", "s" }, { "System.DateTime", new DateTime(2026, 11, 9, 0, 0, 0, DateTimeKind.Utc) },
|
{ "string", "s" }, { "System.DateTime", new DateTime(2026, 11, 9, 0, 0, 0, DateTimeKind.Utc) },
|
||||||
|
// lmxopcua#1100: a Guid input used to fail "unsupported type" out of process.
|
||||||
|
{ "System.Guid", new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") },
|
||||||
};
|
};
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -103,6 +105,24 @@ public sealed class ParityTests
|
|||||||
{ "queue", "var q = new System.Collections.Generic.Queue<long>(); q.Enqueue(3); q.Enqueue(4); return q;" },
|
{ "queue", "var q = new System.Collections.Generic.Queue<long>(); q.Enqueue(3); q.Enqueue(4); return q;" },
|
||||||
{ "list of object", "return new System.Collections.Generic.List<object> { 1, \"a\" };" },
|
{ "list of object", "return new System.Collections.Generic.List<object> { 1, \"a\" };" },
|
||||||
{ "nested list", "return new System.Collections.Generic.List<System.Collections.Generic.List<int>> { new() { 1 } };" },
|
{ "nested list", "return new System.Collections.Generic.List<System.Collections.Generic.List<int>> { new() { 1 } };" },
|
||||||
|
// lmxopcua#1100: both runners return what the OPC UA publish path can represent. A Guid (scalar, array, collection)
|
||||||
|
// is an OPC UA built-in: in process it always reached the client, and the wire now carries it (it was "unsupported
|
||||||
|
// type" out of process). A KeyValuePair[] — what a returned Dictionary becomes — a decimal, an enum, a TimeSpan or a
|
||||||
|
// char has no OPC UA representation: in process the node write threw and the node silently kept its old value and
|
||||||
|
// status, out of process it was "unsupported type"; now both refuse it with the same script-threw reason.
|
||||||
|
{ "guid", "return new System.Guid(\"0f8fad5b-d9cb-469f-a165-70867728950e\");" },
|
||||||
|
{ "guid array", "return new[] { System.Guid.Empty, new System.Guid(\"0f8fad5b-d9cb-469f-a165-70867728950e\") };" },
|
||||||
|
{ "guid list", "return new System.Collections.Generic.List<System.Guid> { System.Guid.Empty };" },
|
||||||
|
{ "dictionary", "return new System.Collections.Generic.Dictionary<int, double> { [1] = 1.5 };" },
|
||||||
|
{ "key-value pair array", "return new[] { new System.Collections.Generic.KeyValuePair<string, int>(\"a\", 1) };" },
|
||||||
|
{ "lazy key-value pairs", "return new System.Collections.Generic.Dictionary<int, int> { [1] = 2 }.Where(p => p.Key > 0);" },
|
||||||
|
{ "key-value pair", "return new System.Collections.Generic.KeyValuePair<int, int>(1, 2);" },
|
||||||
|
{ "decimal", "return 1.5m;" },
|
||||||
|
{ "decimal array", "return new[] { 1.5m };" },
|
||||||
|
{ "enum", "return System.DayOfWeek.Monday;" },
|
||||||
|
{ "time span", "return System.TimeSpan.FromSeconds(1);" },
|
||||||
|
{ "char array", "return new[] { 'a' };" },
|
||||||
|
{ "two-dimensional array", "return new double[1, 1];" },
|
||||||
};
|
};
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -144,6 +164,35 @@ public sealed class ParityTests
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// lmxopcua#1100 controls for the rows above, which would also pass if both runners refused everything or returned
|
||||||
|
/// everything: a Guid array is the same <c>Guid[]</c> in both runners, and a dictionary is refused in both with the
|
||||||
|
/// reason that says what to return instead.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public async Task A_guid_array_crosses_and_a_dictionary_is_refused_in_both_runners()
|
||||||
|
{
|
||||||
|
using var inProcess = new InProcessScriptRunner();
|
||||||
|
await using var outOfProcess = Scripts.Runner(Scripts.Options());
|
||||||
|
var guid = new Guid("0f8fad5b-d9cb-469f-a165-70867728950e");
|
||||||
|
var guids = Scripts.Vt("result-guid-control", $"return new[] {{ System.Guid.Empty, new System.Guid(\"{guid}\") }};");
|
||||||
|
var dictionary = Scripts.Vt("result-dictionary-control", "return new System.Collections.Generic.Dictionary<int, double> { [1] = 1.5 };");
|
||||||
|
|
||||||
|
foreach (var outcome in new[] { await inProcess.RunAsync(guids, Ct), await outOfProcess.RunAsync(guids, Ct) })
|
||||||
|
{
|
||||||
|
outcome.Status.ShouldBe(ScriptRunStatus.Ok, outcome.Reason);
|
||||||
|
outcome.Value.ShouldBeOfType<Guid[]>().ShouldBe([Guid.Empty, guid]);
|
||||||
|
}
|
||||||
|
foreach (var outcome in new[] { await inProcess.RunAsync(dictionary, Ct), await outOfProcess.RunAsync(dictionary, Ct) })
|
||||||
|
{
|
||||||
|
outcome.Status.ShouldBe(ScriptRunStatus.Failed);
|
||||||
|
outcome.Reason.ShouldBe(
|
||||||
|
"script threw: The script returned a value of type 'KeyValuePair<Int32, Double>[]', which an OPC UA node cannot carry; " +
|
||||||
|
"return null, a bool, an integer type, float, double, string, DateTime or Guid, or a one-dimensional array of one of " +
|
||||||
|
"them (convert first, e.g. Convert.ToDouble(x) for a decimal, or the keys and values of a dictionary as two arrays).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task The_worker_holds_a_lazy_result_to_the_configured_cap()
|
public async Task The_worker_holds_a_lazy_result_to_the_configured_cap()
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ public sealed class ProtocolTests
|
|||||||
1.5f, double.NaN, 3.25, "text", string.Empty, new DateTime(2026, 11, 9, 1, 2, 3, DateTimeKind.Utc),
|
1.5f, double.NaN, 3.25, "text", string.Empty, new DateTime(2026, 11, 9, 1, 2, 3, DateTimeKind.Utc),
|
||||||
new[] { 1, 2, 3 }, new short[] { -1, 1 }, new[] { "a", "b" }, new[] { true, false }, Array.Empty<double>(),
|
new[] { 1, 2, 3 }, new short[] { -1, 1 }, new[] { "a", "b" }, new[] { true, false }, Array.Empty<double>(),
|
||||||
new[] { new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc) }, (short)0, 0, 0L, 0.0,
|
new[] { new DateTime(2020, 1, 1, 0, 0, 0, DateTimeKind.Utc) }, (short)0, 0, 0L, 0.0,
|
||||||
|
// lmxopcua#1100: GUID tag (additive).
|
||||||
|
new Guid("0f8fad5b-d9cb-469f-a165-70867728950e"), Guid.Empty, new[] { Guid.Empty, new Guid("0f8fad5b-d9cb-469f-a165-70867728950e") },
|
||||||
];
|
];
|
||||||
return values.Select(v => new[] { v });
|
return values.Select(v => new[] { v });
|
||||||
}
|
}
|
||||||
@@ -54,13 +56,38 @@ public sealed class ProtocolTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void Unsupported_types_are_refused_not_converted()
|
public void Unsupported_types_are_refused_not_converted()
|
||||||
{
|
{
|
||||||
foreach (var value in new object[] { new List<int> { 1 }, 1.5m, Guid.NewGuid(), new { A = 1 }, new int[1, 1], new object[] { 1 } })
|
foreach (var value in new object[]
|
||||||
|
{
|
||||||
|
new List<int> { 1 }, 1.5m, TimeSpan.FromSeconds(1), new { A = 1 }, new int[1, 1], new object[] { 1 },
|
||||||
|
new[] { new KeyValuePair<int, int>(1, 2) },
|
||||||
|
})
|
||||||
{
|
{
|
||||||
VariantCodec.TryEncode(value, out _, out var type).ShouldBeFalse(value.GetType().Name);
|
VariantCodec.TryEncode(value, out _, out var type).ShouldBeFalse(value.GetType().Name);
|
||||||
type.ShouldNotBeNullOrEmpty();
|
type.ShouldNotBeNullOrEmpty();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// lmxopcua#1100: the wire carries every type a script result may have (<see cref="Core.Scripting.ScriptResultMaterializer.PublishableScalarTypes"/>,
|
||||||
|
/// scalar and one-dimensional array), so nothing the materializer passes can fail "unsupported type" in the worker
|
||||||
|
/// alone — the divergence this issue was about (a Guid gave a value in process, "unsupported type" out of process).
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void The_wire_carries_every_publishable_result_type_scalar_and_array()
|
||||||
|
{
|
||||||
|
foreach (var type in Core.Scripting.ScriptResultMaterializer.PublishableScalarTypes)
|
||||||
|
{
|
||||||
|
var scalar = type == typeof(string) ? "s" : Activator.CreateInstance(type)!;
|
||||||
|
var array = Array.CreateInstance(type, 2);
|
||||||
|
array.SetValue(scalar, 0);
|
||||||
|
foreach (var value in new[] { scalar, array })
|
||||||
|
{
|
||||||
|
VariantCodec.TryEncode(value, out var variant, out var unsupported).ShouldBeTrue($"{value.GetType().Name}: {unsupported}");
|
||||||
|
VariantCodec.Decode(Variant.Parser.ParseFrom(variant.ToByteArray()))!.GetType().ShouldBe(value.GetType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void Local_datetime_crosses_as_utc()
|
public void Local_datetime_crosses_as_utc()
|
||||||
{
|
{
|
||||||
@@ -85,6 +112,8 @@ public sealed class ProtocolTests
|
|||||||
var array = new Variant { Type = Variant.Types.TypeTag.Array, Array = new ArrayValue { ElementType = Variant.Types.TypeTag.Byte } };
|
var array = new Variant { Type = Variant.Types.TypeTag.Array, Array = new ArrayValue { ElementType = Variant.Types.TypeTag.Byte } };
|
||||||
array.Array.Items.Add(new Variant { Type = Variant.Types.TypeTag.Byte, U = 1000 });
|
array.Array.Items.Add(new Variant { Type = Variant.Types.TypeTag.Byte, U = 1000 });
|
||||||
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(array));
|
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(array));
|
||||||
|
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Guid, G = ByteString.CopyFrom(new byte[15]) }));
|
||||||
|
Should.Throw<ScriptWorkerProtocolException>(() => VariantCodec.Decode(new Variant { Type = Variant.Types.TypeTag.Guid, S = "x" }));
|
||||||
}
|
}
|
||||||
|
|
||||||
private static Envelope Sample() => new()
|
private static Envelope Sample() => new()
|
||||||
|
|||||||
Reference in New Issue
Block a user