using System.Collections; namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// Thrown when a script's returned value is a sequence that is too large, or of a shape the host cannot take (lmxopcua#1059). public sealed class ScriptResultException : InvalidOperationException { /// Initializes a new instance of the class. /// What was wrong with the returned value. public ScriptResultException(string message) : base(message) { } } /// /// Forces a script's returned sequence to be a bounded, concrete value INSIDE the guarded run (lmxopcua#1059). /// /// /// /// A script can return an iterator (yield) or an unfinished LINQ query. Nothing has run yet when /// Run 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 while(true) yield return or an /// Enumerable.Range(0, int.MaxValue) 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 /// maxElements. /// /// /// What changes: every sequence that is not an array or a string — a lazy one, or a concrete collection such as /// a List<double> or a HashSet<string> — becomes a typed T[] of its /// IEnumerable<T> element type. A sequence whose element type could itself be a sequence /// (object, 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 ForbiddenTypeAnalyzer). 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. /// /// /// The result's TYPE is checked too (lmxopcua#1100): only what the OPC UA publish path can represent passes — /// see / . Anything else (a /// KeyValuePair<K,V>[], which is what a returned dictionary becomes, a decimal, an enum, a /// TimeSpan, a tuple) fails the run with a 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". /// /// /// Concrete collections used to be returned as-is too (lmxopcua#1092): in process the host got the /// List<T> 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. /// /// /// 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 Scripting:Runner=OutOfProcess contains those. See docs/VirtualTags.md. /// /// /// The ONE result rule for both runners (lmxopcua#1064): the in-process and the /// out-of-process ScriptWorker both call right after a value script returns, /// inside the run, with the node's Scripting:MaxResultElements (the worker receives it in its /// Hello). Public for that reason only. /// /// public static class ScriptResultMaterializer { /// Materialises as described on the type. /// The script's returned value. /// The element cap; zero or negative disables the cap (a lazy sequence is still materialised, unbounded). /// The value the host should see. /// The sequence exceeds the cap, or its element type is an open slot. 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; } } /// /// 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 (SdkValueBoundary.FromClr) 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 (VariantCodec) carries. Pinned against both by tests. /// public static IReadOnlyList 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), ]; /// /// Whether a returned value of can reach an OPC UA client (lmxopcua#1100): a /// scalar, or a one-dimensional array whose element type is one. /// /// /// A jagged array (int[][], byte[][]) is refused (lmxopcua#1104), although /// SdkValueBoundary.FromClr 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. /// /// The runtime type of the returned value. /// true when the publish path can represent the value. 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 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(); 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 / IReadOnlyCollection without the non-generic ICollection (HashSet, …): 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)); }