Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs
T
Joseph Doherty ec17a83aea fix(scripting): #1109 byte[][] stays refused with a ByteString-specific reason
A script result has no ByteString-array form (its only byte shape is one flat
Byte array) and the worker wire has no ByteString or nested-array tag, so
byte[][] is left refused with every other jagged array (no new wire tag). Its
reason now says it is not an array of ByteStrings and offers both forms that
publish: a flat byte[] (SelectMany) or a string[] of Base64 blobs. Pinned by
ScriptResultMaterializerTests.
2026-12-04 22:09:47 -05:00

234 lines
12 KiB
C#

using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
/// <summary>
/// lmxopcua#1059 — a script that returns an iterator or an unfinished LINQ query used to hand the host a sequence
/// nothing had run yet; the host then enumerated it on its own thread, outside the guard's timeout / allocation sample
/// and with no element bound. The guard now materialises the result inside the guarded run, bounded.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ScriptResultMaterializerTests
{
private static IEnumerable<double> Endless() { var i = 0.0; while (true) yield return i++; }
[Fact]
public void A_lazy_sequence_becomes_a_typed_array_and_runs_now()
{
var ran = 0;
var lazy = Enumerable.Range(0, 4).Select(i => { ran++; return (double)i; });
ran.ShouldBe(0);
var result = ScriptResultMaterializer.Materialize(lazy, 100).ShouldBeOfType<double[]>();
result.ShouldBe([0.0, 1.0, 2.0, 3.0]);
ran.ShouldBe(4);
}
[Fact]
public void A_sequence_past_the_cap_is_cut_off_not_enumerated_forever()
{
var ex = Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Endless(), 1000));
ex.Message.ShouldContain("1000");
}
[Fact]
public void A_sequence_of_exactly_the_cap_is_accepted_boundary()
=> ScriptResultMaterializer.Materialize(Enumerable.Range(0, 5).Select(i => (long)i), 5)
.ShouldBeOfType<long[]>().Length.ShouldBe(5);
[Fact]
public void A_lazy_sequence_of_an_open_slot_type_is_refused()
{
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (object)i), 100));
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => new List<int> { i }), 100));
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (IComparable)i), 100));
}
[Fact]
public void Arrays_strings_scalars_and_null_pass_through_unchanged_positive_controls()
{
var array = new[] { 1.0, 2.0 };
ScriptResultMaterializer.Materialize(array, 100).ShouldBeSameAs(array);
ScriptResultMaterializer.Materialize("abc", 100).ShouldBe("abc");
ScriptResultMaterializer.Materialize(42, 100).ShouldBe(42);
ScriptResultMaterializer.Materialize(null, 100).ShouldBeNull();
}
/// <summary>
/// lmxopcua#1092: a concrete collection becomes the same typed array a lazy sequence does — the out-of-process
/// worker's wire has no collection type, so returning the collection as-is made the two runners disagree.
/// </summary>
[Fact]
public void A_concrete_collection_becomes_a_typed_array()
{
ScriptResultMaterializer.Materialize(new List<int> { 1, 2 }, 100).ShouldBeOfType<int[]>().ShouldBe([1, 2]);
ScriptResultMaterializer.Materialize(new HashSet<string> { "a" }, 100).ShouldBeOfType<string[]>().ShouldBe(["a"]);
ScriptResultMaterializer.Materialize(new Queue<double>([1.5]), 100).ShouldBeOfType<double[]>().ShouldBe([1.5]);
ScriptResultMaterializer.Materialize(new List<int>(new int[100]), 100).ShouldBeOfType<int[]>().Length.ShouldBe(100);
}
[Fact]
public void A_collection_of_an_open_or_unknown_element_type_is_refused_like_a_lazy_one()
{
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<object> { 1 }, 100))
.Message.ShouldContain("collection of 'Object'");
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<List<int>> { new() { 1 } }, 100));
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new System.Collections.ArrayList { 1 }, 100))
.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>[]'");
}
/// <summary>
/// lmxopcua#1104: an array of arrays is refused in both runners (the in-process runner used to publish it as an
/// array of Variants, the worker answered "unsupported type"), with a reason that says to flatten it — a
/// <c>byte[][]</c> included. The scalar-array positive controls are in
/// <see cref="Every_publishable_type_passes_scalar_and_array_positive_controls"/>.
/// </summary>
[Fact]
public void A_jagged_array_is_refused_with_a_flatten_hint()
{
foreach (var value in new object[] { new[] { new[] { 1 } }, new[] { new byte[] { 1 } }, new[] { new[] { "a" } }, new[] { new[] { new[] { 1.0 } } } })
{
ScriptResultMaterializer.IsPublishable(value.GetType()).ShouldBeFalse(value.GetType().Name);
var message = Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(value, 100), value.GetType().Name).Message;
message.ShouldContain("which an OPC UA node cannot carry: an array of arrays");
message.ShouldContain("SelectMany");
}
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new[] { new[] { 1 } }, 100))
.Message.ShouldStartWith("The script returned a value of type 'Int32[][]'");
}
/// <summary>
/// lmxopcua#1109: <c>byte[][]</c> stays refused (a script result has no ByteString-array form and the worker wire has
/// no tag for one — none was added), but its reason says so and offers the two forms that do publish. A lazy /
/// collection sequence of byte[] is refused earlier (its element type is itself a sequence), before it runs.
/// </summary>
[Fact]
public void A_byte_array_of_arrays_is_refused_with_a_ByteString_specific_reason()
{
ScriptResultMaterializer.IsPublishable(typeof(byte[][])).ShouldBeFalse();
var message = Should.Throw<ScriptResultException>(
() => ScriptResultMaterializer.Materialize(new[] { new byte[] { 1, 2 }, new byte[] { 3 } }, 100)).Message;
message.ShouldStartWith("The script returned a value of type 'Byte[][]', which an OPC UA node cannot carry: an array of arrays");
message.ShouldContain("cannot be an array of ByteStrings");
message.ShouldContain("SelectMany");
message.ShouldContain("Convert.ToBase64String");
var ran = 0;
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<byte[]> { new byte[] { 1 } }, 100));
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(
Enumerable.Range(0, 2).Select(i => { ran++; return new[] { (byte)i }; }), 100));
ran.ShouldBe(0);
// The flat forms the reason offers do publish.
ScriptResultMaterializer.Materialize(new byte[] { 1, 2, 3 }, 100).ShouldBeOfType<byte[]>();
ScriptResultMaterializer.Materialize(new[] { "AQI=" }, 100).ShouldBeOfType<string[]>();
}
[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]);
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]
public void An_oversized_array_or_collection_is_refused_by_the_same_cap()
{
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new double[101], 100));
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<int>(new int[101]), 100));
}
[Fact]
public void A_zero_cap_disables_the_bound_but_still_materialises()
=> ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => i), 0).ShouldBeOfType<int[]>();
[Fact]
public void The_options_clamp_a_non_positive_cap_to_the_default()
{
var sanitized = new ScriptingOptions { MaxResultElements = 0 }.Sanitized(out var notes);
sanitized.MaxResultElements.ShouldBe(ScriptingOptions.DefaultMaxResultElements);
notes.ShouldContain(n => n.Contains("MaxResultElements"));
new ScriptingOptions().Sanitized(out var none).MaxResultElements.ShouldBe(ScriptingOptions.DefaultMaxResultElements);
none.ShouldBeEmpty();
}
// ---- through the guard, with a real compiled script ----
private static ScriptEvaluator<FakeScriptContext, object?> Compile(string source) =>
ScriptEvaluator<FakeScriptContext, object?>.Compile(source);
[Fact]
public async Task The_guard_hands_the_host_a_materialised_array_not_a_live_query()
{
var guard = new ScriptRunGuard();
using var eval = Compile("return System.Linq.Enumerable.Range(0, 3).Select(i => (double)i * 2);");
var result = await guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
result.ShouldBeOfType<double[]>().ShouldBe([0.0, 2.0, 4.0]);
}
[Fact]
public async Task The_guard_cuts_off_an_endless_lazy_sequence_inside_the_run_and_does_not_strike_the_script()
{
var guard = new ScriptRunGuard(new ScriptingOptions { MaxResultElements = 1000, QuarantineAfterConsecutiveTimeouts = 1 });
using var eval = Compile("return System.Linq.Enumerable.Range(0, int.MaxValue).Select(i => (double)i);");
var ct = TestContext.Current.CancellationToken;
await Should.ThrowAsync<ScriptResultException>(() => guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), ct));
await Should.ThrowAsync<ScriptResultException>(() => guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), ct));
guard.IsQuarantined("k", out _).ShouldBeFalse("a refused result is a failed run, not a timeout strike");
guard.InFlightCount.ShouldBe(0);
}
[Fact]
public async Task The_guard_charges_the_enumeration_to_the_allocation_budget()
{
// 2 MB budget; the sequence materialises ~100k strings — the allocation happens during enumeration, which used to
// be outside the sample entirely.
var guard = new ScriptRunGuard(new ScriptingOptions { MaxAllocBytesPerRun = 1024 * 1024 });
using var eval = Compile("return System.Linq.Enumerable.Range(0, 90000).Select(i => new string('x', 64) + i);");
await Should.ThrowAsync<ScriptQuarantinedException>(() =>
guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
guard.IsQuarantined("k", out var reason).ShouldBeTrue();
reason!.ShouldContain("allocated");
}
}