ec17a83aea
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.
221 lines
14 KiB
C#
221 lines
14 KiB
C#
using System.Collections;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
|
|
|
/// <summary>Thrown when a script's returned value is a sequence that is too large, or of a shape the host cannot take (lmxopcua#1059).</summary>
|
|
public sealed class ScriptResultException : InvalidOperationException
|
|
{
|
|
/// <summary>Initializes a new instance of the <see cref="ScriptResultException"/> class.</summary>
|
|
/// <param name="message">What was wrong with the returned value.</param>
|
|
public ScriptResultException(string message) : base(message)
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Forces a script's returned sequence to be a bounded, concrete value INSIDE the guarded run (lmxopcua#1059).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// A script can return an iterator (<c>yield</c>) or an unfinished LINQ query. Nothing has run yet when
|
|
/// <c>Run</c> returns: the host then enumerates it on ITS thread — outside the guard's timeout and
|
|
/// allocation sampling, with no bound on the element count — so a <c>while(true) yield return</c> or an
|
|
/// <c>Enumerable.Range(0, int.MaxValue)</c> would hang or exhaust the publish path rather than the script's own
|
|
/// run. The guard therefore materialises the result right after the script returns, on the same pool thread, so
|
|
/// the enumeration is charged to the run (timeout, orphan slot, allocation budget) and is capped at
|
|
/// <c>maxElements</c>.
|
|
/// </para>
|
|
/// <para>
|
|
/// What changes: every sequence that is not an array or a string — a lazy one, or a concrete collection such as
|
|
/// a <c>List<double></c> or a <c>HashSet<string></c> — becomes a typed <c>T[]</c> of its
|
|
/// <c>IEnumerable<T></c> element type. A sequence whose element type could itself be a sequence
|
|
/// (<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
|
|
/// returned as-is (fully built by the run) but are still held to the element cap. Everything else — scalars,
|
|
/// 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>
|
|
/// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the
|
|
/// <c>List<T></c> itself, while the out-of-process worker, whose wire carries arrays but no collection
|
|
/// type, answered "unsupported type" for the same script. Copying a collection into an array is the one value
|
|
/// both runners can give; a collection that reports its size is held to the cap BEFORE it is copied.
|
|
/// </para>
|
|
/// <para>
|
|
/// This does NOT make the in-process runner a hard sandbox: memory exhaustion inside the run and a
|
|
/// non-terminating loop are still only contained by the guard's after-the-fact allocation sample and its timeout
|
|
/// (an orphaned thread). Only <c>Scripting:Runner=OutOfProcess</c> contains those. See docs/VirtualTags.md.
|
|
/// </para>
|
|
/// <para>
|
|
/// The ONE result rule for both runners (lmxopcua#1064): the in-process <see cref="ScriptRunGuard"/> and the
|
|
/// out-of-process <c>ScriptWorker</c> both call <see cref="Materialize"/> right after a value script returns,
|
|
/// inside the run, with the node's <c>Scripting:MaxResultElements</c> (the worker receives it in its
|
|
/// <c>Hello</c>). Public for that reason only.
|
|
/// </para>
|
|
/// </remarks>
|
|
public static class ScriptResultMaterializer
|
|
{
|
|
/// <summary>Materialises <paramref name="value"/> as described on the type.</summary>
|
|
/// <param name="value">The script's returned value.</param>
|
|
/// <param name="maxElements">The element cap; zero or negative disables the cap (a lazy sequence is still materialised, unbounded).</param>
|
|
/// <returns>The value the host should see.</returns>
|
|
/// <exception cref="ScriptResultException">The sequence exceeds the cap, or its element type is an open slot.</exception>
|
|
public static object? Materialize(object? value, int maxElements)
|
|
{
|
|
switch (value)
|
|
{
|
|
case null or string:
|
|
return value;
|
|
case Array array:
|
|
EnsurePublishable(array.GetType());
|
|
EnforceCap(array.Length, maxElements);
|
|
return array;
|
|
case ICollection collection:
|
|
EnforceCap(collection.Count, maxElements);
|
|
return MaterializeSequence(collection, maxElements, "collection");
|
|
case IEnumerable sequence:
|
|
return MaterializeSequence(sequence, maxElements, IsGenericCollection(sequence.GetType()) ? "collection" : "lazy sequence");
|
|
default:
|
|
EnsurePublishable(value.GetType());
|
|
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 one.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// A jagged array (<c>int[][]</c>, <c>byte[][]</c>) is refused (lmxopcua#1104), although
|
|
/// <c>SdkValueBoundary.FromClr</c> would take it as an array of Variants: a script-fed node has a scalar DataType
|
|
/// (Int32 with ValueRank one dimension, say), so a Variant-of-arrays value is not what its DataType declares, and
|
|
/// the out-of-process wire has no nested-array tag — the in-process runner published it while the worker answered
|
|
/// "unsupported type". Refused here, inside the run, both runners fail it with the same reason.
|
|
/// </remarks>
|
|
/// <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 && PublishableScalarTypes.Contains(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;
|
|
// lmxopcua#1109: byte[][] reads like "an array of ByteStrings", which OPC UA does have (the OpcUaClient driver even
|
|
// surfaces a ByteString[] as byte[][]). But a script result has no ByteString-array form: the result rule's only
|
|
// byte shape is a one-dimensional Byte array, and the out-of-process wire (VariantCodec) has no ByteString or
|
|
// nested-array tag — adding one is deliberately out of scope. So byte[][] stays refused with every other jagged
|
|
// array; the reason just says so explicitly and offers the string[] form, which does publish.
|
|
if (type == typeof(byte[][]))
|
|
throw new ScriptResultException(
|
|
"The script returned a value of type 'Byte[][]', which an OPC UA node cannot carry: an array of arrays has " +
|
|
"no representation on a node whose DataType is a scalar type, and a script result cannot be an array of " +
|
|
"ByteStrings either (its only byte shape is one flat Byte array); return one flat byte[] " +
|
|
"(e.g. a.SelectMany(x => x).ToArray()) or a string[] of encoded blobs " +
|
|
"(e.g. a.Select(Convert.ToBase64String).ToArray()).");
|
|
if (type.IsArray && type.GetElementType()!.IsArray)
|
|
throw new ScriptResultException(
|
|
$"The script returned a value of type '{Describe(type)}', which an OPC UA node cannot carry: an array of " +
|
|
"arrays has no representation on a node whose DataType is a scalar type; return one flat one-dimensional " +
|
|
"array (e.g. a.SelectMany(x => x).ToArray()) or publish each inner array from its own tag.");
|
|
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)
|
|
{
|
|
var elementType = ElementTypeOf(sequence.GetType())
|
|
?? throw new ScriptResultException(
|
|
$"The script returned a {what} ({sequence.GetType().Name}) with no IEnumerable<T> element type; " +
|
|
"return an array of a concrete type (double[], string[], …).");
|
|
if (IsOpenSlot(elementType))
|
|
throw new ScriptResultException(
|
|
$"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[], …).");
|
|
// 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?>();
|
|
foreach (var item in sequence)
|
|
{
|
|
if (maxElements > 0 && items.Count >= maxElements)
|
|
throw new ScriptResultException(
|
|
$"The script returned a sequence of more than {maxElements} elements (Scripting:MaxResultElements); " +
|
|
"it was cut off while being materialised.");
|
|
items.Add(item);
|
|
}
|
|
var result = Array.CreateInstance(elementType, items.Count);
|
|
for (var i = 0; i < items.Count; i++) result.SetValue(items[i], i);
|
|
return result;
|
|
}
|
|
|
|
private static void EnforceCap(int count, int maxElements)
|
|
{
|
|
if (maxElements > 0 && count > maxElements)
|
|
throw new ScriptResultException(
|
|
$"The script returned a collection of {count} elements, over the {maxElements}-element limit (Scripting:MaxResultElements).");
|
|
}
|
|
|
|
private static Type? ElementTypeOf(Type type)
|
|
{
|
|
Type? found = null;
|
|
foreach (var i in type.GetInterfaces().Append(type))
|
|
{
|
|
if (!i.IsGenericType || i.GetGenericTypeDefinition() != typeof(IEnumerable<>)) continue;
|
|
var arg = i.GetGenericArguments()[0];
|
|
if (found is not null && found != arg) return null; // ambiguous
|
|
found = arg;
|
|
}
|
|
return found;
|
|
}
|
|
|
|
// ICollection<T> / IReadOnlyCollection<T> without the non-generic ICollection (HashSet<T>, …): only the wording.
|
|
private static bool IsGenericCollection(Type type) =>
|
|
type.GetInterfaces().Any(i => i.IsGenericType
|
|
&& (i.GetGenericTypeDefinition() == typeof(ICollection<>) || i.GetGenericTypeDefinition() == typeof(IReadOnlyCollection<>)));
|
|
|
|
private static bool IsOpenSlot(Type t) =>
|
|
t == typeof(object) || t.IsInterface || t.IsAbstract
|
|
|| (t != typeof(string) && typeof(IEnumerable).IsAssignableFrom(t));
|
|
}
|