diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 8c382e090..6e25a85e1 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -190,8 +190,16 @@ the runtime would refuse rejects the deploy with `ScriptCompileFailed`, naming t script, the seam it was compiled for and the entities using it — so an error the editor showed can no longer be deployed silently. Two differences from the editor to know: the gate compiles each script **as the seam that uses it** (a predicate -must return `bool`; the editor analyses every script as a VirtualTag body), and it -only checks scripts something enabled uses. See `docs/VirtualTags.md` +must return `bool`), and it only checks scripts something enabled uses. The editor +matches the gate's seam since #1025: the analysis endpoints take an optional `mode` +(`value` default | `alarmPredicate`), the editor wraps the source as +`bool Run(ScriptGlobals)` in predicate mode, and the ScriptEdit +page has an **Analyse as** selector that defaults to *predicate* when scripted alarms +are the script's only users (a script also used as a VirtualTag/Calculation defaults to +value; pick whichever seam you are authoring for). The per-equipment VirtualTag and +Calculation editors are always value mode. Known remaining gap: a body that lacks a +`return` on some path (CS0161) is not flagged while you type (a deliberate +no-phantom-marker rule) but is refused at deploy. See `docs/VirtualTags.md` §"Deploy-time script compile gate" for modes, caching and the upgrade note. ### Runtime safety (what happens after publish) @@ -231,6 +239,19 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: `Scripting:MaxAllocBytesPerRun` (64 MB) is quarantined. This is sampled after the run returns, so a run that OOMs the process first is not stopped — that needs an out-of-process runner (→ #750). +- **A returned sequence is materialised inside the run, bounded (#1059).** A script can return an + iterator (`yield`) or an unfinished LINQ query: nothing has run when `Run` returns, so the host used + to enumerate it on its own thread — outside the timeout and the allocation sample, with no element + bound. The guard now enumerates a lazy sequence into a typed array (`double[]` for an + `IEnumerable`) on the run's own thread, so the work is charged to the timeout, the orphan slot + and the allocation budget, and refuses one past `Scripting:MaxResultElements` (default 100 000; also + caps a returned array / collection) with a failed run (Bad, script log) — not a timeout strike. A lazy + sequence whose element type is `object`, an interface or another collection is refused: the host + copies and compares a returned array recursively, so an open-slot array can nest or contain itself. + Arrays, lists, strings and scalars are unchanged. **Still in-process-only limits** (the boundary is + `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 + sequence. See `docs/VirtualTags.md` §"Known resource limits (accepted trade-offs)". - **Out of process (opt-in, lmxopcua#780).** `Scripting:Runner=OutOfProcess` moves the virtual-tag and Calculation seams' compiled runs — and the scripted-alarm predicates, when `Scripting:Runner:Seams` lists `ScriptedAlarm` — into `ScriptWorker` processes, where a @@ -246,7 +267,7 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: handler that throws on every frame cannot overflow the stack while unwinding (lmxopcua#971 review); the editor does not show it and does not flag recursion, and bounded recursion still works. -- **Configuration keys and their ranges.** All four knobs are node-wide (the +- **Configuration keys and their ranges.** The numeric knobs are node-wide (the `Scripting` appsettings section, shared by virtual tags, Calculation tags and scripted alarms) and are clamped when bound, with one startup Warning per clamped value: @@ -255,6 +276,7 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: |---|---|---| | `Scripting:RunTimeout` | `00:00:02` (2 s) | zero or negative becomes the default; above `00:01:00` becomes 60 s. The per-run budget of virtual tags and scripted-alarm predicates (lmxopcua#779 — alarms used to fall back to 250 ms). Calculation tags keep their per-driver `runTimeoutMs`. | | `Scripting:MaxAllocBytesPerRun` | `67108864` (64 MB) | `0` (or negative) disables the budget; a positive value below `1048576` (1 MB) becomes 1 MB | + | `Scripting:MaxResultElements` | `100000` | most elements a returned array / collection / materialised sequence may hold (#1059); zero or negative becomes the default | | `Scripting:QuarantineAfterConsecutiveTimeouts` | `3` | `1`–`1000` | | `Scripting:StuckOrphanQuarantineFactor` | `10` | `0` (or negative) disables the rule; above `1000` becomes `1000`; `NaN` becomes the default. In-process runner only (lmxopcua#780 P4) | @@ -519,8 +541,12 @@ hold `\`, `"`, braces, line breaks or non-ASCII text (`RawPaths.ValidateSegment` A `` with a malformed escape (`\e`) is left as written for the compiler to report. Only regular `"…"` literals are path literals: a `{{equip}}/…` token inside a verbatim (`@"…"`), -interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted** (and not checked) — keep the -token in a regular literal. +interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted**, so since #1056 it is refused +instead of silently reading Bad at runtime: the editor flags it (`OTSCRIPT_EQUIPLITERAL`, an error) and +the deploy gate fails the script (`equip token not substituted — …`), both through +`EquipTokenLiteralScanner`. Keep the token in a regular literal. (Only a `ctx.GetTag` / +`ctx.SetVirtualTag` path argument is scanned; a `{{equip}}` token in a Calculation script is not +substituted in any literal form — the seam does no substitution.) --- diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 661528b3e..a416d5716 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -67,12 +67,12 @@ The deploy gate compiles every script the deployment will run before the deploym | `Warn` | Logged and appended to the accepted deployment message; the deploy succeeds. | | `Off` | The gate does not run. | -Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the AdminUI waits 10 s for a deploy answer, so on a very large fleet the first deploy after a restart can report a timeout while it carries on — the next is cached. +Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the singleton warms the checker in the background as it starts (#1024) and the AdminUI waits 45 s for a deploy answer (10 s for ack/shelve), so only a very large fleet deployed within seconds of a restart can still report an `OutcomeUnknown` timeout while the deploy carries on — the next is cached. #### Known resource limits (accepted trade-offs) -The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen — the review found BCL members that do exactly that over script-built data (see "Deep or cyclic data" in the sandbox section), and the analyzer now refuses the constructs that build it; a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". +The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen — the review found BCL members that do exactly that over script-built data (see "Deep or cyclic data" in the sandbox section), and the analyzer now refuses the constructs that build it; a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. **Returned sequences and the sandbox boundary (lmxopcua#1059).** A script that returns an iterator or an unfinished LINQ query used to hand the host a sequence nothing had run — enumerated later on the host's thread, outside the timeout and allocation sample. `ScriptRunGuard` now materialises a returned lazy sequence into a typed array on the run's own thread (`ScriptResultMaterializer`), capped at `Scripting:MaxResultElements` (default 100 000, also applied to returned arrays/collections); an over-cap sequence or one whose element type is open (`object`, an interface, another collection) fails the run (Bad + script log, not a timeout strike). **What the in-process runner does NOT contain** — and what `Scripting:Runner=OutOfProcess` does: memory exhaustion inside a run (sampled after the fact), a non-terminating loop (one orphaned pool thread, then quarantine) and the same two inside the enumeration of a returned sequence. Decision: document the boundary rather than add in-process memory accounting — an in-process run cannot be pre-empted, so any in-process "limit" is advisory. **Rule for the allow-list:** the host recurses over script-built data (`OwnedDataSample.CopyLegacy`, `VirtualTagActor.SameValue` over a returned array; a value's `ToString`/`Equals`/`GetHashCode` in logging and dedup), so any type added to `ForbiddenTypeAnalyzer.AllowedTypes` later must be checked for recursive `ToString`/`Equals`/`GetHashCode` over script-built (possibly cyclic or deeply nested) data before it is allowed. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs new file mode 100644 index 000000000..208eb3703 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs @@ -0,0 +1,85 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; + +/// +/// Finds ctx.GetTag(…) / ctx.SetVirtualTag(…) calls whose path argument carries the +/// {{equip}} token in a literal form the substitution does NOT rewrite (lmxopcua#1056). +/// +/// +/// +/// EquipmentScriptPaths.SubstituteEquipmentToken rewrites the token only inside a REGULAR "…" +/// path literal. A verbatim (@"…"), raw ("""…""") or interpolated ($"…") literal used to pass +/// the editor and the deploy gate and then reach the runtime with the token still in the path — the tag read +/// Bad for as long as it was deployed, with no error anywhere. Both the editor +/// (OTSCRIPT_EQUIPLITERAL) and the deploy gate () now run this +/// one scan and refuse such a script, so "the editor accepts ⇔ publish accepts" holds. +/// +/// +/// Same receiver guard as (a member access on the identifier ctx), so +/// comments, other receivers and a token in a string that is not a path argument are never flagged. +/// +/// +public static class EquipTokenLiteralScanner +{ + private const string EquipToken = "{{equip}}"; + + /// One offending path literal. + /// The offending literal's span in the scanned source. + /// The operator-facing explanation. + public sealed record Finding(TextSpan Span, string Message); + + /// The offending path literals of , in source order. + /// The script source (any {{equip}} token still unresolved is fine). + /// The findings; empty when none. + public static IReadOnlyList Find(string? source) + { + if (string.IsNullOrEmpty(source) || !source.Contains(EquipToken, StringComparison.Ordinal)) + return []; + var tree = CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(kind: SourceCodeKind.Script)); + var findings = new List(); + foreach (var inv in tree.GetRoot().DescendantNodes().OfType()) + { + if (inv.Expression is not MemberAccessExpressionSyntax + { + Expression: IdentifierNameSyntax { Identifier.ValueText: "ctx" }, + Name.Identifier.ValueText: "GetTag" or "SetVirtualTag", + } member) + continue; + if (inv.ArgumentList.Arguments.Count == 0) continue; + var path = inv.ArgumentList.Arguments[0].Expression; + var form = OffendingForm(path); + if (form is null) continue; + findings.Add(new Finding( + path.Span, + $"The {EquipToken} token is inside a {form} string literal in ctx.{member.Name.Identifier.ValueText}(...), " + + "where it is NOT substituted — the path would reach the runtime unresolved and read Bad. " + + $"Use a regular \"…\" literal: ctx.{member.Name.Identifier.ValueText}(\"{EquipToken}/\").")); + } + return findings; + } + + private static string? OffendingForm(ExpressionSyntax path) + { + switch (path) + { + case LiteralExpressionSyntax lit when lit.IsKind(SyntaxKind.StringLiteralExpression): + { + var text = lit.Token.Text; + var form = text.StartsWith("@\"", StringComparison.Ordinal) ? "verbatim" + : text.StartsWith("\"\"\"", StringComparison.Ordinal) ? "raw" + : null; + return form is not null && ((string?)lit.Token.Value ?? "").StartsWith(EquipToken, StringComparison.Ordinal) + ? form : null; + } + case InterpolatedStringExpressionSyntax interpolated + when interpolated.ToString().Contains(EquipToken, StringComparison.Ordinal): + return "interpolated"; + default: + return null; + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs index 501b59490..1629b3096 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs @@ -85,6 +85,12 @@ public static class ForbiddenTypeAnalyzer /// Func<…>). A nested type is allowed when its containing type is. Every System.Exception /// subclass declared in the System namespace is allowed in addition to this list. /// + /// + /// lmxopcua#1059: before adding a type here, check its ToString / Equals / GetHashCode for + /// recursion over script-built data — the host copies and compares a returned value recursively + /// (OwnedDataSample.CopyLegacy, VirtualTagActor.SameValue) and formats it into logs, so a type that + /// recurses over a cyclic or deeply nested value a script can build would overflow the HOST's stack after the run. + /// public static readonly IReadOnlyList AllowedTypes = [ // Primitives and core value types. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs index 4445cfffb..0a7fa361f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs @@ -112,6 +112,13 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker var source = request.Source ?? string.Empty; try { + // lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted, so the + // script would compile and then read a tag path that cannot resolve. The editor runs the same scan. + var unsubstituted = EquipTokenLiteralScanner.Find(source); + if (unsubstituted.Count > 0) + return new CachedVerdict( + ["equip token not substituted — " + string.Join("; ", unsubstituted.Select(f => f.Message))], + Cacheable: true); if (request.Kind == ScriptContextKind.AlarmPredicate) { var extraction = DependencyExtractor.Extract(source); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs new file mode 100644 index 000000000..b3d2cf357 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptResultMaterializer.cs @@ -0,0 +1,117 @@ +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: a lazy sequence (an that is neither an array, a string nor an +/// ) 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 and already-concrete collections are returned as-is (they +/// were fully built by the run) but are still held to the element cap. Everything else — scalars, strings, +/// null — is untouched. +/// +/// +/// 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. +/// +/// +internal 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: + EnforceCap(array.Length, maxElements); + return array; + case ICollection collection: + EnforceCap(collection.Count, maxElements); + return value; + case IEnumerable sequence: + return MaterializeLazy(sequence, maxElements); + default: + return value; + } + } + + private static object MaterializeLazy(IEnumerable sequence, int maxElements) + { + var elementType = ElementTypeOf(sequence.GetType()) + ?? throw new ScriptResultException( + $"The script returned a lazy sequence ({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 lazy sequence of '{elementType.Name}', which can contain another sequence or itself; " + + "return a typed array of a concrete type (double[], string[], …)."); + + 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; + } + + private static bool IsOpenSlot(Type t) => + t == typeof(object) || t.IsInterface || t.IsAbstract + || (t != typeof(string) && typeof(IEnumerable).IsAssignableFrom(t)); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs index 979e477fd..576b76adf 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptRunGuard.cs @@ -85,6 +85,7 @@ public sealed class ScriptRunGuard private readonly long _maxAllocBytesPerRun; private readonly int _quarantineThreshold; private readonly double _stuckFactor; + private readonly int _maxResultElements; private readonly ILogger _logger; private int _inFlight; private long _started; @@ -102,6 +103,7 @@ public sealed class ScriptRunGuard _maxAllocBytesPerRun = options.MaxAllocBytesPerRun; _quarantineThreshold = options.QuarantineAfterConsecutiveTimeouts; _stuckFactor = options.StuckOrphanQuarantineFactor; + _maxResultElements = options.MaxResultElements; _logger = logger ?? Log.Logger; } @@ -251,8 +253,13 @@ public sealed class ScriptRunGuard // ScriptEvaluator.RunAsync executes the compiled delegate synchronously and returns a completed // task, so the after-sample is taken on the same thread, right after the script returned. var pending = evaluator.RunAsync(context, runToken); - slot.AllocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; var value = await pending.ConfigureAwait(false); + // lmxopcua#1059: a returned iterator / unfinished LINQ query has run nothing yet. Enumerate it HERE, on the + // run's own thread, so the work is charged to the timeout + allocation sample and bounded — never on the + // host's publish path. (Only a reference-typed result can be a sequence.) + if (!typeof(TResult).IsValueType) + value = (TResult)ScriptResultMaterializer.Materialize(value, _maxResultElements)!; + slot.AllocatedBytes = GC.GetAllocatedBytesForCurrentThread() - before; succeeded = true; return value; } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs index 3e141e10d..f5449f19e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptingOptions.cs @@ -28,6 +28,9 @@ public sealed class ScriptingOptions /// Default : 64 MB. public const long DefaultMaxAllocBytesPerRun = 64L * 1024 * 1024; + /// Default : 100 000. + public const int DefaultMaxResultElements = 100_000; + /// Default : 3. public const int DefaultQuarantineAfterConsecutiveTimeouts = 3; @@ -53,6 +56,15 @@ public sealed class ScriptingOptions /// public long MaxAllocBytesPerRun { get; set; } = DefaultMaxAllocBytesPerRun; + /// + /// The most elements a script's returned array / collection / sequence may hold (lmxopcua#1059). A lazy sequence + /// (iterator, unfinished LINQ query) the script returns is enumerated into an array INSIDE the guarded run — so the + /// enumeration is charged to the run's timeout and allocation budget instead of happening unbounded on the + /// host's publish path — and cut off with a past this count. Zero or negative + /// becomes the default. Default 100 000. + /// + public int MaxResultElements { get; set; } = DefaultMaxResultElements; + /// /// Consecutive timeouts after which the script is quarantined: no further runs are dispatched, every /// evaluation reports Bad, and the quarantine lifts only on a source change, a redeploy or an explicit @@ -174,6 +186,13 @@ public sealed class ScriptingOptions alloc = MinMaxAllocBytesPerRun; } + var maxResultElements = MaxResultElements; + if (maxResultElements <= 0) + { + notes.Add($"{SectionName}:{nameof(MaxResultElements)} {maxResultElements} is not positive; using the default {DefaultMaxResultElements}."); + maxResultElements = DefaultMaxResultElements; + } + var runTimeout = RunTimeout; if (runTimeout <= TimeSpan.Zero) { @@ -196,6 +215,7 @@ public sealed class ScriptingOptions { RunTimeout = runTimeout, MaxAllocBytesPerRun = alloc, + MaxResultElements = maxResultElements, QuarantineAfterConsecutiveTimeouts = threshold, StuckOrphanQuarantineFactor = factor, Runner = Runner, diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs index 3bc8dac64..54c24b6ea 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Calculation/CalculationDriverFactoryExtensions.cs @@ -136,6 +136,7 @@ public static class CalculationDriverFactoryExtensions resolved.MaxAllocBytesPerRun = nodeScripting.MaxAllocBytesPerRun; resolved.QuarantineAfterConsecutiveTimeouts = nodeScripting.QuarantineAfterConsecutiveTimeouts; resolved.StuckOrphanQuarantineFactor = nodeScripting.StuckOrphanQuarantineFactor; + resolved.MaxResultElements = nodeScripting.MaxResultElements; } if (maxAllocBytesPerRun is { } alloc) resolved.MaxAllocBytesPerRun = alloc; if (quarantineAfterConsecutiveTimeouts is { } n) resolved.QuarantineAfterConsecutiveTimeouts = n; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs index f662b6b8c..84604d50a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/AdminOperationsClient.cs @@ -10,28 +10,47 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients; /// /// backed by the cluster singleton registered in /// AddOtOpcUaControlPlane. Resolves the singleton proxy from -/// at construction time; each call Asks the proxy with a 10s timeout. +/// at construction time; each call Asks the proxy with a 10s timeout (45s for the deploy trigger, #1024). /// public sealed class AdminOperationsClient : IAdminOperationsClient { - private static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10); + /// The general ask timeout (ack / shelve / probes). + internal static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10); + + /// + /// #1024: the deploy trigger's own ask timeout. The compose runs the Roslyn script compile gate, and on a + /// large fleet a COLD checker (first deploy after a central restart) can take well past 10 s; the singleton + /// warms the checker at start, but the first deploy may still race that. A timeout is still + /// , never a failure — this just makes it rarer. + /// + internal static readonly TimeSpan DefaultDeployAskTimeout = TimeSpan.FromSeconds(45); private readonly IActorRef _proxy; private readonly TimeSpan AskTimeout; + private readonly TimeSpan DeployAskTimeout; /// Initializes a new instance of the AdminOperationsClient. /// The actor registry to resolve the admin operations singleton proxy. - public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout) + public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout, DefaultDeployAskTimeout) { } - /// Test seam: the same client with a caller-chosen ask timeout. + /// Test seam: the same client with a caller-chosen ask timeout (also used for the deploy trigger). /// The actor registry to resolve the admin operations singleton proxy. /// How long to wait for the singleton's reply. - internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout) + internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout) : this(registry, askTimeout, askTimeout) + { + } + + /// Test seam: caller-chosen general and deploy-trigger ask timeouts. + /// The actor registry to resolve the admin operations singleton proxy. + /// How long to wait for the singleton's reply to ack/shelve. + /// How long to wait for the singleton's reply to StartDeployment. + internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout, TimeSpan deployAskTimeout) { _proxy = registry.Get(); AskTimeout = askTimeout; + DeployAskTimeout = deployAskTimeout; } /// @@ -48,10 +67,10 @@ public sealed class AdminOperationsClient : IAdminOperationsClient var correlationId = CorrelationId.NewId(); var msg = new StartDeployment(createdBy, correlationId, deploymentId); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct); - linked.CancelAfter(AskTimeout); + linked.CancelAfter(DeployAskTimeout); try { - return await _proxy.Ask(msg, AskTimeout, linked.Token); + return await _proxy.Ask(msg, DeployAskTimeout, linked.Token); } catch (Exception ex) when (ex is AskTimeoutException || (ex is OperationCanceledException && !ct.IsCancellationRequested)) @@ -60,7 +79,7 @@ public sealed class AdminOperationsClient : IAdminOperationsClient StartDeploymentOutcome.OutcomeUnknown, deploymentId, RevisionHash: null, - Message: $"No reply from the deployment service within {AskTimeout.TotalSeconds:0} s, so it is not known " + + Message: $"No reply from the deployment service within {DeployAskTimeout.TotalSeconds:0} s, so it is not known " + $"whether the deployment was created. If it was, it carries id {deploymentId.Value}; check the " + "deployment history (or GET /api/deployments/" + deploymentId.Value + ") before retrying.", correlationId); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor index 815db2549..fe555eac0 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor @@ -75,8 +75,19 @@ else

Source

+ @* #1025: the editor analyses the script as the seam that runs it — the deploy gate compiles a scripted-alarm + predicate as `bool Run(AlarmPredicateContext)`, a VirtualTag/Calculation script as a value script. + Defaults from the script's current users; the author can switch for a not-yet-used script. *@ +
+ + +
+ AriaLabel="Script source code" ReadOnly="@_busy" Mode="@_mode" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
SHA-256 hash is computed automatically on save.
@@ -114,6 +125,7 @@ else private string _deleteMessage = ""; private DeleteIntent? _deleteIntent; private MonacoEditor? _editor; + private string _mode = ScriptAnalysisModes.Value; private ScriptProblemReport _markers = ScriptProblemReport.Empty; private sealed record DeleteIntent(string Id, byte[] RowVersion); @@ -126,6 +138,10 @@ else { if (Current(generation) && !_busy && ReferenceEquals(form, _form)) form.SourceCode = value; } + private void ChangeMode(string? value, long generation) + { + if (Current(generation)) _mode = ScriptAnalysisModes.IsPredicate(value) ? ScriptAnalysisModes.AlarmPredicate : ScriptAnalysisModes.Value; + } private void OnMarkersChanged(ScriptProblemReport report, long generation) { if (Current(generation)) _markers = report; @@ -143,7 +159,7 @@ else ++_confirmationEpoch; _loaded = _busy = _confirmDeleteVisible = false; _existing = null; _editor = null; _deleteIntent = null; - _form = new(); _markers = ScriptProblemReport.Empty; _error = _loadError = null; + _form = new(); _mode = ScriptAnalysisModes.Value; _markers = ScriptProblemReport.Empty; _error = _loadError = null; try { if (!string.IsNullOrEmpty(id)) @@ -153,6 +169,12 @@ else var existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == id); if (!Current(generation)) return; _existing = existing; + if (existing is not null) + { + var usage = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.ClassifyAsync(db, id); + if (!Current(generation)) return; + _mode = usage.DefaultMode; + } if (existing is not null) _form = new FormModel { ScriptId = existing.ScriptId, Name = existing.Name, SourceCode = existing.SourceCode, RowVersion = existing.RowVersion.ToArray() }; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor index dc917ca90..f6edeedb9 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/MonacoEditor.razor @@ -53,6 +53,13 @@ ///
[Parameter] public string? EquipmentId { get; set; } + /// + /// Which seam the script is analysed as (; lmxopcua#1025): null/value for a + /// VirtualTag / Calculation script, alarmPredicate for a scripted-alarm predicate (must return bool). + /// Changing it re-analyses the live editor. + /// + [Parameter] public string? Mode { get; set; } + /// /// Fires whenever Monaco's diagnostic marker set updates (after the 500 ms debounce, and only for the response /// to the CURRENT text — superseded responses are dropped in the JS). Feeds ScriptProblemsList; the @@ -67,6 +74,7 @@ private readonly string _id = Guid.NewGuid().ToString("N"); private string _lastSentValue = ""; private string _lastSentAriaLabel = ""; + private string? _lastSentMode; private bool _lastSentReadOnly; private string AccessibleLabel => string.IsNullOrWhiteSpace(AriaLabel) ? "Code editor" : AriaLabel; private bool _disposed; @@ -86,6 +94,7 @@ _lastSentValue = Value ?? ""; var createdLabel = AccessibleLabel; var createdReadOnly = ReadOnly; + var createdMode = Mode; _initializing = true; try { @@ -100,6 +109,7 @@ language = Language, readOnly = createdReadOnly, equipmentId = EquipmentId, + mode = Mode, maxSyncBytes = ScriptEditorLimits.MaxEditorSyncBytes, reportMarkers = MarkersChanged.HasDelegate, maxReportedMarkers = ScriptEditorLimits.MaxReportedMarkers, @@ -110,6 +120,7 @@ _initialized = true; _lastSentAriaLabel = createdLabel; _lastSentReadOnly = createdReadOnly; + _lastSentMode = createdMode; } catch (InvalidOperationException) { @@ -137,6 +148,11 @@ _lastSentReadOnly = ReadOnly; await SafeInvokeAsync("MonacoBlazor.setEditorOption", "set editor read-only state", _id, "readOnly", _lastSentReadOnly); } + if (!_disposed && _initialized && !string.Equals(Mode, _lastSentMode, StringComparison.Ordinal)) + { + _lastSentMode = Mode; + await SafeInvokeAsync("MonacoBlazor.setMode", "set script analysis mode", _id, _lastSentMode); + } if (!_disposed && _initialized && AccessibleLabel != _lastSentAriaLabel) { _lastSentAriaLabel = AccessibleLabel; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs index 1227957a8..ccfc3d445 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisContracts.cs @@ -1,22 +1,43 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; +/// +/// Which seam the editor analyses a script as (lmxopcua#1025). The deploy gate compiles each script as the seam that +/// uses it, so the editor has to wrap the source the same way: a value script is +/// object Run(ScriptGlobals<VirtualTagContext>) (VirtualTag and Calculation share it); a scripted-alarm +/// predicate is bool Run(ScriptGlobals<AlarmPredicateContext>). Carried as a string on the wire; null, +/// blank or anything unrecognised means . +/// +public static class ScriptAnalysisModes +{ + /// A VirtualTag / Calculation value script (the default). + public const string Value = "value"; + + /// A scripted-alarm predicate: must return bool. + public const string AlarmPredicate = "alarmPredicate"; + + /// True when selects the predicate shape. + /// The wire value. + /// Whether it names . + public static bool IsPredicate(string? mode) => string.Equals(mode, AlarmPredicate, StringComparison.OrdinalIgnoreCase); +} + // EquipmentId (optional) carries the owning-equipment context the {{equip}}/ completion + // diagnostic need to resolve reference effective names. Null on the shared ScriptEdit page (no single // equipment) — the equip-ref features are then inert, matching the deploy gate (which only resolves per -// owning equipment). -public record DiagnoseRequest(string Code, string? EquipmentId = null); +// owning equipment). Mode (optional) selects the seam the script is analysed as — see ScriptAnalysisModes. +public record DiagnoseRequest(string Code, string? EquipmentId = null, string? Mode = null); public record DiagnoseResponse(IReadOnlyList Markers); public record DiagnosticMarker(int Severity, int StartLineNumber, int StartColumn, int EndLineNumber, int EndColumn, string Message, string Code); -public record CompletionsRequest(string CodeText, int Line, int Column, string? EquipmentId = null); +public record CompletionsRequest(string CodeText, int Line, int Column, string? EquipmentId = null, string? Mode = null); public record CompletionsResponse(IReadOnlyList Items); public record CompletionItem(string Label, string InsertText, string Detail, string Kind, int InsertTextRules = 0); -public record HoverRequest(string CodeText, int Line, int Column, string? EquipmentId = null); +public record HoverRequest(string CodeText, int Line, int Column, string? EquipmentId = null, string? Mode = null); public record HoverResponse(string? Markdown); -public record SignatureHelpRequest(string CodeText, int Line, int Column); +public record SignatureHelpRequest(string CodeText, int Line, int Column, string? Mode = null); public record SignatureHelpResponse(string? Label, IReadOnlyList? Parameters, int ActiveParameter); public record SignatureHelpParameter(string Label, string? Documentation); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs index c0402fb88..48e8e9b45 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -3,6 +3,7 @@ using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.Logging; using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; using ZB.MOM.WW.OtOpcUa.Core.Scripting; using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; @@ -27,8 +28,6 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; /// public sealed class ScriptAnalysisService { - private static readonly SandboxConfig Sandbox = ScriptSandbox.Build(typeof(VirtualTagContext)); - private static readonly string Preamble = BuildPreamble(); private static readonly CSharpCompilationOptions CompileOptions = new( OutputKind.DynamicallyLinkedLibrary, optimizationLevel: OptimizationLevel.Release, allowUnsafe: false, warningLevel: 4, nullableContextOptions: NullableContextOptions.Enable); @@ -44,52 +43,66 @@ public sealed class ScriptAnalysisService _logger = logger; } - // Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the - // Run(ScriptGlobals) shape), except the analysis return type is - // `object` so a shared script stays valid regardless of any virtual tag's DataType. - private static string BuildPreamble() - { - var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};")); - var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals"; - return usings + "\n\n" - + "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n" - + "public static class CompiledScript\n{\n" - + $" public static object Run({globalsType} globals)\n {{\n" - + " var ctx = globals.ctx;\n#line 1\n"; - } - - private static SyntaxTree WrapAndParse(string userSource, CancellationToken ct) - => CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct); - /// - /// The process-wide compilation every analysis derives from. Its sandbox reference set is bound ONCE - /// (forced here by resolving System.Object); keeps - /// that binding, so a request only re-binds the user's tree instead of the whole reference set. It is - /// immutable, so sharing it across circuits and requests is thread-safe. + /// One analysis shape (lmxopcua#1025): the sandbox + wrapper the deploy gate compiles a seam's script with, and + /// the process-wide every analysis of that seam derives from. Its sandbox reference + /// set is bound ONCE (forced by resolving System.Object); + /// keeps that binding, so a request only re-binds the user's tree. Immutable, so shared across circuits/requests. /// - internal static readonly CSharpCompilation BaseCompilation = CreateBaseCompilation(); - - private static CSharpCompilation CreateBaseCompilation() + private sealed class Shape { - var compilation = CSharpCompilation.Create( - "ScriptAnalysis", new[] { WrapAndParse("", CancellationToken.None) }, Sandbox.References, CompileOptions); - _ = compilation.GetSpecialType(SpecialType.System_Object); - return compilation; + public Shape(Type contextType, string returnType) + { + Sandbox = ScriptSandbox.Build(contextType); + // Mirrors ScriptEvaluator's wrapper EXACTLY (usings from the sandbox + the Run(ScriptGlobals) + // shape). The value shape's return type is `object` so a shared script stays valid regardless of any + // virtual tag's DataType; the predicate shape is `bool`, exactly as the alarm engine compiles it. + var usings = string.Join("\n", Sandbox.Imports.Select(i => $"using {i};")); + var globalsType = $"global::{typeof(ScriptGlobals<>).Namespace}.ScriptGlobals"; + Preamble = usings + "\n\n" + + "namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Compiled;\n" + + "public static class CompiledScript\n{\n" + + $" public static {returnType} Run({globalsType} globals)\n {{\n" + + " var ctx = globals.ctx;\n#line 1\n"; + var compilation = CSharpCompilation.Create( + "ScriptAnalysis", new[] { Parse("", CancellationToken.None) }, Sandbox.References, CompileOptions); + _ = compilation.GetSpecialType(SpecialType.System_Object); + BaseCompilation = compilation; + } + + public SandboxConfig Sandbox { get; } + public string Preamble { get; } + public CSharpCompilation BaseCompilation { get; } + + public SyntaxTree Parse(string userSource, CancellationToken ct) + => CSharpSyntaxTree.ParseText(Preamble + (userSource ?? "") + "\n }\n}\n", cancellationToken: ct); } + private static readonly Shape ValueShape = new(typeof(VirtualTagContext), "object"); + private static readonly Shape PredicateShape = new(typeof(AlarmPredicateContext), "bool"); + + private static Shape ShapeFor(string? mode) => ScriptAnalysisModes.IsPredicate(mode) ? PredicateShape : ValueShape; + + /// The process-wide value-shape compilation (test seam; the predicate shape has its own). + internal static CSharpCompilation BaseCompilation => ValueShape.BaseCompilation; + // userSource is appended after Preamble, then the method/class are closed. Every analysis derives straight // from the shared BaseCompilation: the analysis endpoints are minimal-API handlers, so a scoped service lives // for one HTTP request and a per-instance lineage would never be more than one step long. private static (SyntaxTree Tree, CSharpCompilation Compilation, SemanticModel Model, int PreambleLength) Analyze( - string userSource, CancellationToken ct) + string userSource, string? mode, CancellationToken ct) { - var tree = WrapAndParse(userSource, ct); - var compilation = BaseCompilation.ReplaceSyntaxTree(BaseCompilation.SyntaxTrees[0], tree); - return (tree, compilation, compilation.GetSemanticModel(tree), Preamble.Length); + var shape = ShapeFor(mode); + var tree = shape.Parse(userSource, ct); + var compilation = shape.BaseCompilation.ReplaceSyntaxTree(shape.BaseCompilation.SyntaxTrees[0], tree); + return (tree, compilation, compilation.GetSemanticModel(tree), shape.Preamble.Length); } /// Test seam: the compilation one analysis of runs against. - internal CSharpCompilation CompilationFor(string userSource) => Analyze(Normalize(userSource), CancellationToken.None).Compilation; + /// The script source. + /// The analysis mode (); null = value. + internal CSharpCompilation CompilationFor(string userSource, string? mode = null) + => Analyze(Normalize(userSource), mode, CancellationToken.None).Compilation; // editor (line,col) in USER-source coords -> physical offset in the wrapped document private static int OffsetInWrapped(string userSource, int line, int column, int preambleLength) @@ -121,7 +134,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.Code); - var (tree, compilation, _, preambleLength) = Analyze(code, ct); + var (tree, compilation, _, preambleLength) = Analyze(code, req.Mode, ct); var markers = new List(); // (1) Roslyn — surface ONLY compile errors, the same severity that actually blocks a @@ -149,10 +162,16 @@ public sealed class ScriptAnalysisService // (3) DependencyExtractor — spans are offsets in the normalized user source; map directly. foreach (var r in DependencyExtractor.Extract(code).Rejections) markers.Add(ToUserMarker(code, r.Span, r.Message, "OTSCRIPT_DYNPATH")); + // (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted — + // the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too. + foreach (var f in EquipTokenLiteralScanner.Find(code)) + markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL")); // (4) ctx.SetVirtualTag(...) is inert at runtime — a WARNING (severity 4), never an error: publish // accepts the script, so the editor must too; the marker just puts the hover's caveat in the Problems list. foreach (var inv in SetVirtualTagCalls(tree.GetRoot(ct), preambleLength)) - markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4, SetVirtualTagInertMessage, "OTSCRIPT_SETVTAG_INERT")); + markers.Add(ToMarker(tree.GetMappedLineSpan(inv.Span), 4, + ScriptAnalysisModes.IsPredicate(req.Mode) ? SetVirtualTagPredicateMessage : SetVirtualTagInertMessage, + "OTSCRIPT_SETVTAG_INERT")); return new DiagnoseResponse(Bound(markers)); } @@ -228,6 +247,10 @@ public sealed class ScriptAnalysisService : m with { Message = ScriptProblems.Truncate(m.Message, ScriptEditorLimits.MaxDiagnosticMessageChars) }) .ToList(); + private const string SetVirtualTagPredicateMessage = + "ctx.SetVirtualTag(...) throws in a scripted-alarm predicate: predicates must be side-effect free. The script " + + "compiles and publishes, but every evaluation fails — move the write into a virtual tag the predicate reads."; + private const string SetVirtualTagInertMessage = "ctx.SetVirtualTag(...) has no effect at runtime: cross-tag writes are dropped in single-tag mode (the " + "cascade engine is not wired into the host). The script compiles and publishes, but this write will not " + @@ -282,7 +305,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.CodeText); - var (tree, _, model, preambleLength) = Analyze(code, ct); + var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct); var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength); var root = await tree.GetRootAsync(ct); // position is the offset just AFTER the caret; -1 finds the token the caret sits at/just-after (e.g. the dot in "ctx."). @@ -402,7 +425,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.CodeText); - var (tree, _, model, preambleLength) = Analyze(code, ct); + var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct); var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength); var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1)); @@ -504,7 +527,7 @@ public sealed class ScriptAnalysisService { ct.ThrowIfCancellationRequested(); var code = Normalize(req.CodeText); - var (tree, _, model, preambleLength) = Analyze(code, ct); + var (tree, _, model, preambleLength) = Analyze(code, req.Mode, ct); var position = OffsetInWrapped(code, req.Line, req.Column, preambleLength); var token = tree.GetRoot(ct).FindToken(Math.Max(0, position - 1)); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs index a1d1709cb..423e7c2bb 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs @@ -21,6 +21,42 @@ public static class ScriptUsage /// How many using rows are named in the refusal before it summarises the rest. private const int NamedLimit = 5; + /// Which seams use a script. + /// An (any) VirtualTag or Calculation tag runs it as a value script. + /// An (any) scripted alarm runs it as its predicate. + public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate) + { + /// + /// The editor analysis mode (ScriptAnalysisModes) a script should open in (lmxopcua#1025): the predicate + /// shape only when scripted alarms are its sole users — a script also run as a value script stays a value + /// script (the author can switch), and an unused script is a value script. + /// + public string DefaultMode => + UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate : ScriptAnalysis.ScriptAnalysisModes.Value; + } + + /// Classifies which seams use (same rows, same Calculation parser as the delete check). + /// The config context. + /// The script. + /// Cancellation token. + /// Where the script is used. + public static async Task ClassifyAsync(OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentException.ThrowIfNullOrEmpty(scriptId); + var predicate = await db.ScriptedAlarms.AsNoTracking().AnyAsync(a => a.PredicateScriptId == scriptId, ct); + var value = await db.VirtualTags.AsNoTracking().AnyAsync(v => v.ScriptId == scriptId, ct); + if (!value) + { + var calcCandidates = await db.Tags.AsNoTracking() + .Where(t => t.TagConfig.Contains(scriptId)) + .Select(t => t.TagConfig) + .ToListAsync(ct); + value = calcCandidates.Any(c => string.Equals(DraftValidator.ParseScriptId(c), scriptId, StringComparison.Ordinal)); + } + return new SeamUsage(value, predicate); + } + /// /// Describes every row that references , or returns when /// nothing does and the script may be deleted. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js index 3d35a9ca2..9545b266f 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/wwwroot/js/monaco-init.js @@ -52,6 +52,9 @@ // registered csharp providers (which only receive the model) can thread it into the {{equip}}/ // completion + diagnostics. Null on the shared ScriptEdit page (equip-ref features inert there). function equipmentIdOf(model) { return (model && model.__otEquipmentId) || null; } + // The analysis mode (#1025): "alarmPredicate" analyses the script as a scripted-alarm predicate (bool Run), anything + // else as a value script. Stamped on the model like the equipment id; changeable later via setMode. + function modeOf(model) { return (model && model.__otMode) || null; } function registerCSharpProviders() { monaco.languages.registerCompletionItemProvider("csharp", { @@ -59,7 +62,7 @@ provideCompletionItems: async function (model, position, context, token) { try { const data = await postAnalysis("completions", - { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model) }, + { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model), mode: modeOf(model) }, token); if (!data) return { suggestions: [] }; const word = model.getWordUntilPosition(position); @@ -97,7 +100,7 @@ provideHover: async function (model, position, token) { try { const data = await postAnalysis("hover", - { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model) }, + { codeText: model.getValue(), line: position.lineNumber, column: position.column, equipmentId: equipmentIdOf(model), mode: modeOf(model) }, token); if (!data || !data.markdown) return null; return { contents: [{ value: data.markdown }] }; @@ -119,7 +122,7 @@ provideSignatureHelp: async function (model, position, token) { try { const data = await postAnalysis("signature-help", - { codeText: model.getValue(), line: position.lineNumber, column: position.column }, + { codeText: model.getValue(), line: position.lineNumber, column: position.column, mode: modeOf(model) }, token); if (!data || !data.label) return null; return { @@ -145,7 +148,7 @@ const resp = await fetch("/api/script-analysis/diagnostics", { method: "POST", credentials: "same-origin", signal: signal, headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ code: model.getValue(), equipmentId: equipmentIdOf(model) }) + body: JSON.stringify({ code: model.getValue(), equipmentId: equipmentIdOf(model), mode: modeOf(model) }) }); if (!resp.ok) return []; const data = await resp.json(); @@ -257,7 +260,7 @@ }); // Stamp the owning-equipment id on the model so the global csharp providers can thread it into the // {{equip}}/ completion + diagnostics (null on the shared ScriptEdit page). - try { const m0 = editor.getModel(); if (m0) m0.__otEquipmentId = options.equipmentId || null; } catch (x) {} + try { const m0 = editor.getModel(); if (m0) { m0.__otEquipmentId = options.equipmentId || null; m0.__otMode = options.mode || null; } } catch (x) {} const e = { editor: editor, dotNetRef: dotNetRef, dirty: false, maxSyncBytes: options.maxSyncBytes || 0, reportMarkers: !!options.reportMarkers, @@ -296,6 +299,13 @@ editors[id] = e; if (options.language === "csharp") e.scheduleDiagnostics(); } + // Switches the analysis mode of a live editor (#1025) and re-runs diagnostics so the markers match the new seam. + function setMode(id, mode) { + const e = editors[id]; if (!e) return; + const model = e.editor.getModel(); if (!model) return; + model.__otMode = mode || null; + if (e.scheduleDiagnostics) e.scheduleDiagnostics(); + } function setEditorOption(id, name, value) { const e = editors[id]; if (!e) return; // Note: monaco.editor.setTheme is global — it re-themes every editor on the page, not just this id. @@ -331,5 +341,5 @@ delete editors[id]; } - window.MonacoBlazor = { createEditor, setValue, getValue, setMarkers, setEditorOption, format, revealLine, dispose }; + window.MonacoBlazor = { createEditor, setMode, setValue, getValue, setMarkers, setEditorOption, format, revealLine, dispose }; })(); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index 247fbe0a7..d5a8fffa8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -33,6 +33,8 @@ public sealed class AdminOperationsActor : ReceiveActor private readonly ScriptCompileGateMode _scriptCompileGateMode; + private readonly bool _warmScriptGateOnStart; + /// /// The coordinator's apply deadline. A Dispatching row with no expected-ack rows that is older /// than this is a lost dispatch, closed by the in-flight check (fix round 1 / I7). @@ -66,6 +68,7 @@ public sealed class AdminOperationsActor : ReceiveActor /// #950: how long an /alerts ack/shelve waits for the nodes' verdicts; defaults to . /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. /// How a refused script is treated (Error default | Warn | Off). + /// #1024: when true the checker's cache is warmed in the background as the actor starts (production wiring), so the first deploy after a restart is not a cold Roslyn compile. /// Props configured to create an AdminOperationsActor. public static Props Props( IDbContextFactory dbFactory, @@ -76,10 +79,11 @@ public sealed class AdminOperationsActor : ReceiveActor TimeSpan? applyDeadline = null, TimeSpan? alarmVerdictWindow = null, IDeployScriptChecker? scriptChecker = null, - ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) => + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error, + bool warmScriptGateOnStart = false) => Akka.Actor.Props.Create(() => new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, - alarmVerdictWindow, scriptChecker, scriptCompileGateMode)); + alarmVerdictWindow, scriptChecker, scriptCompileGateMode, warmScriptGateOnStart)); /// Initializes a new instance of the AdminOperationsActor. /// Factory for creating config database contexts. @@ -91,6 +95,7 @@ public sealed class AdminOperationsActor : ReceiveActor /// #950: the /alerts verdict collection window. /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. /// How a refused script is treated (Error default | Warn | Off). + /// #1024: warm the checker's cache in the background on start. public AdminOperationsActor( IDbContextFactory dbFactory, IActorRef coordinator, @@ -100,8 +105,10 @@ public sealed class AdminOperationsActor : ReceiveActor TimeSpan? applyDeadline = null, TimeSpan? alarmVerdictWindow = null, IDeployScriptChecker? scriptChecker = null, - ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error, + bool warmScriptGateOnStart = false) { + _warmScriptGateOnStart = warmScriptGateOnStart; _scriptChecker = scriptCompileGateMode == ScriptCompileGateMode.Off ? null : scriptChecker; _scriptCompileGateMode = scriptCompileGateMode; _alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow; @@ -127,6 +134,19 @@ public sealed class AdminOperationsActor : ReceiveActor Receive(HandleShelveAlarm); } + /// + /// #1024: warms the script compile gate's cache off the actor thread as the singleton starts (and on every + /// failover re-spawn), so the FIRST deploy after a central restart is not a cold Roslyn compile of the whole + /// fleet's scripts racing the AdminUI's ask timeout. Fire-and-forget; the warm-up is best-effort and a + /// concurrent deploy shares the in-flight compiles (the checker's per-key lazy). + /// + protected override void PreStart() + { + base.PreStart(); + if (_warmScriptGateOnStart && _scriptChecker is { } checker) + _ = Task.Run(() => WarmScriptCompileGateAsync(checker)); + } + /// /// The reply text for an unexpected server-side failure (R03:4.1): a fixed sentence plus the request's /// correlation id, never ex.Message — a SqlException or UriFormatException message carries diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs index 9849f0530..f4dc5c739 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs @@ -157,7 +157,8 @@ public static class ServiceCollectionExtensions // is past the coordinator's deadline, so the two must never drift. return AdminOperationsActor.Props(dbFactory, coordinator, probes, mode, meshRouter, applyDeadline: DeployTimings.ApplyDeadline, - scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode); + scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode, + warmScriptGateOnStart: true); }, singletonOptions); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/EquipTokenLiteralScannerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/EquipTokenLiteralScannerTests.cs new file mode 100644 index 000000000..f7a49a6c8 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/EquipTokenLiteralScannerTests.cs @@ -0,0 +1,80 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// lmxopcua#1056 — {{equip}}/<RefName> is only substituted inside a REGULAR "…" path literal. In a +/// verbatim (@"…"), raw ("""…""") or interpolated ($"…") literal the token used to be +/// silently left in the path, so the tag read Bad at runtime while the editor and the deploy gate were green. The +/// scanner finds those forms; the editor (OTSCRIPT_EQUIPLITERAL) and the deploy gate both refuse them. +/// +[Trait("Category", "Unit")] +public sealed class EquipTokenLiteralScannerTests +{ + [Theory] + [InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value;")] + [InlineData("return ctx.GetTag(\"\"\"{{equip}}/speed\"\"\").Value;")] + [InlineData("return ctx.GetTag($\"{{equip}}/speed\").Value;")] + [InlineData("return ctx.GetTag($@\"{{equip}}/speed\").Value;")] + [InlineData("ctx.SetVirtualTag(@\"{{equip}}/speed\", 1); return 0;")] + public void A_token_inside_a_non_regular_path_literal_is_found(string source) + { + var findings = EquipTokenLiteralScanner.Find(source); + findings.ShouldHaveSingleItem(); + findings[0].Message.ShouldContain("regular"); + source.Substring(findings[0].Span.Start, findings[0].Span.Length).ShouldContain("{{equip}}"); + } + + [Theory] + [InlineData("return ctx.GetTag(\"{{equip}}/speed\").Value;")] // the supported form + [InlineData("return ctx.GetTag(@\"Plant/Drv/speed\").Value;")] // verbatim without the token + [InlineData("return ctx.GetTag(\"A\").Value; // @\"{{equip}}/speed\"")] // a comment + [InlineData("var s = @\"{{equip}}/speed\"; return ctx.GetTag(\"A\").Value;")] // not a path argument + [InlineData("return other.GetTag(@\"{{equip}}/speed\");")] // not ctx + [InlineData("return ctx.GetTag($\"Plant/{1}\").Value;")] // interpolated, no token + [InlineData("return 1;")] + public void Everything_else_is_not_flagged_positive_controls(string source) + => EquipTokenLiteralScanner.Find(source).ShouldBeEmpty(); + + [Fact] + public void Every_offending_call_is_reported_in_source_order() + { + var findings = EquipTokenLiteralScanner.Find( + "var a = ctx.GetTag(@\"{{equip}}/a\"); var b = ctx.GetTag(\"{{equip}}/ok\"); var c = ctx.GetTag($\"{{equip}}/c\"); return 0;"); + findings.Count.ShouldBe(2); + findings[0].Span.Start.ShouldBeLessThan(findings[1].Span.Start); + } + + [Fact] + public void The_regular_literal_form_really_is_the_one_substitution_handles() + { + // Pins the premise: the same source with a regular literal substitutes, the verbatim one does not. + var map = new Dictionary { ["speed"] = "Plant/Drv/dev/speed" }; + ZB.MOM.WW.OtOpcUa.Commons.Types.EquipmentScriptPaths + .SubstituteEquipmentToken("return ctx.GetTag(\"{{equip}}/speed\").Value;", map) + .ShouldContain("Plant/Drv/dev/speed"); + ZB.MOM.WW.OtOpcUa.Commons.Types.EquipmentScriptPaths + .SubstituteEquipmentToken("return ctx.GetTag(@\"{{equip}}/speed\").Value;", map) + .ShouldContain("{{equip}}/speed"); + } + + [Theory] + [InlineData(ScriptContextKind.VirtualTag)] + [InlineData(ScriptContextKind.AlarmPredicate)] + public void The_deploy_gate_refuses_such_a_script(ScriptContextKind kind) + { + var source = kind == ScriptContextKind.AlarmPredicate + ? "return ctx.GetTag(@\"{{equip}}/speed\").Value is not null;" + : "return ctx.GetTag(@\"{{equip}}/speed\").Value;"; + var result = new RoslynDeployScriptChecker().Check( + [new DeployScriptCheckRequest(kind, source)], TestContext.Current.CancellationToken).Single(); + result.Passed.ShouldBeFalse(); + result.Problems.ShouldContain(p => p.Contains("{{equip}}") && p.Contains("regular")); + + // positive control: the supported spelling of the same script passes + var ok = new RoslynDeployScriptChecker().Check( + [new DeployScriptCheckRequest(kind, source.Replace("@\"", "\""))], TestContext.Current.CancellationToken).Single(); + ok.Passed.ShouldBeTrue(string.Join("; ", ok.Problems)); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs new file mode 100644 index 000000000..4b03c8eac --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptResultMaterializerTests.cs @@ -0,0 +1,121 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// 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. +/// +[Trait("Category", "Unit")] +public sealed class ScriptResultMaterializerTests +{ + private static IEnumerable 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(); + + 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(() => 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().Length.ShouldBe(5); + + [Fact] + public void A_lazy_sequence_of_an_open_slot_type_is_refused() + { + Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (object)i), 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => new List { i }), 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (IComparable)i), 100)); + } + + [Fact] + public void Arrays_collections_strings_scalars_and_null_pass_through_unchanged_positive_controls() + { + var array = new[] { 1.0, 2.0 }; + ScriptResultMaterializer.Materialize(array, 100).ShouldBeSameAs(array); + var list = new List { 1, 2 }; + ScriptResultMaterializer.Materialize(list, 100).ShouldBeSameAs(list); + ScriptResultMaterializer.Materialize("abc", 100).ShouldBe("abc"); + ScriptResultMaterializer.Materialize(42, 100).ShouldBe(42); + ScriptResultMaterializer.Materialize(null, 100).ShouldBeNull(); + } + + [Fact] + public void An_oversized_array_or_collection_is_refused_by_the_same_cap() + { + Should.Throw(() => ScriptResultMaterializer.Materialize(new double[101], 100)); + Should.Throw(() => ScriptResultMaterializer.Materialize(new List(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(); + + [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 Compile(string source) => + ScriptEvaluator.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().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(() => guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), ct)); + await Should.ThrowAsync(() => 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(() => + guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken)); + guard.IsQuarantined("k", out var reason).ShouldBeTrue(); + reason!.ShouldContain("allocated"); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs index 2bc92e2dd..c0436e720 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRunGuardTests.cs @@ -310,41 +310,41 @@ public sealed class ScriptRunGuardTests } /// - /// Positive control for the stuck rule: a 2x overrun (one timeout, refusals while the orphan is young) + /// Positive control for the stuck rule: a short overrun (one timeout, a refusal while the orphan is young) /// is NOT quarantined, and once the orphan completes the script evaluates normally again. /// + /// + /// lmxopcua#1038: this used to be a WALL-CLOCK test — the orphan was a script spinning 200 ms against a 100 ms budget, + /// and the test thread had to land its refused call inside the 100 ms between the timeout and the orphan finishing + /// on its own. Any stall of the test thread longer than that (a GC pause, thread-pool starvation from the parallel + /// test classes, a descheduled runner) let the orphan finish first, so the "refused" call simply ran and returned 7 — + /// the guard right, the test's window too narrow (reproduced deterministically by delaying the test thread 150 ms + /// after the timeout). Now the orphan is HELD until the test releases it (a signal, like + /// ), so it cannot finish early, and the budget is 500 ms against the default 10x + /// stuck factor so the held orphan would have to age past 5 s before the refusal call could be read as "stuck" — the + /// refusal path takes microseconds. The test no longer depends on how fast it runs, only on the order of events. + /// [Fact] - public async Task A_2x_overrun_is_not_quarantined_and_resumes_evaluating_once_the_orphan_completes() + public async Task A_short_overrun_is_not_quarantined_and_resumes_evaluating_once_the_orphan_completes() { var guard = new ScriptRunGuard(); - const string source = - """ - var ms = (int)(ctx.GetTag("spinMs").Value ?? 0); - var end = System.DateTime.UtcNow.AddMilliseconds(ms); - while (System.DateTime.UtcNow < end) { } - return 7; - """; - using var eval = Compile(source); + using var spin = Compile(BriefSpinScript); + using var fast = Compile(FastScript); var ct = TestContext.Current.CancellationToken; - var timeout = TimeSpan.FromMilliseconds(100); + var timeout = TimeSpan.FromMilliseconds(500); + var held = new FakeScriptContext(); - FakeScriptContext Ctx(int spinMs) - { - var c = new FakeScriptContext(); - c.Tags["spinMs"] = new Core.Abstractions.DataValueSnapshot(spinMs, 0u, c.Now, c.Now); - return c; - } + // The orphan: held past its budget (one timeout) — and it stays running until released. + await Should.ThrowAsync(() => Run(guard, "k", BriefSpinScript, spin, timeout, ct, held)); + // …so the very next trigger is deterministically refused while it is young. + await Should.ThrowAsync(() => Run(guard, "k", BriefSpinScript, spin, timeout, ct, held)); + guard.IsQuarantined("k", out _).ShouldBeFalse("a short overrun is far below the 10x stuck threshold"); - // Warm the JIT so the first measured run's overrun is the script's, not the compiler's. - (await guard.RunAsync("k", source, eval, Ctx(0), TimeSpan.FromSeconds(5), ct)).ShouldBe(7); + await ReleaseAndDrain(guard, held); - // 2x overrun: 200 ms against a 100 ms budget — times out, then is refused while it finishes. - await Should.ThrowAsync(() => guard.RunAsync("k", source, eval, Ctx(200), timeout, ct)); - await Should.ThrowAsync(() => guard.RunAsync("k", source, eval, Ctx(0), timeout, ct)); - await WaitForIdle(guard); - - guard.IsQuarantined("k", out _).ShouldBeFalse("a 2x overrun is far below the 10x stuck threshold"); - (await guard.RunAsync("k", source, eval, Ctx(0), timeout, ct)).ShouldBe(7, "the script resumes evaluating"); + guard.IsQuarantined("k", out _).ShouldBeFalse(); + (await Run(guard, "k", BriefSpinScript, spin, timeout, ct, new FakeScriptContext { Released = true })).ShouldBe(1, + "the script resumes evaluating once the orphan has completed"); guard.QuarantinedCount.ShouldBe(0); } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs index a6df40c42..19705cbcb 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/AdminOperationsClientDeployTimeoutTests.cs @@ -65,6 +65,38 @@ public sealed class AdminOperationsClientDeployTimeoutTests : TestKit .DeploymentId.ShouldBe(result.DeploymentId.Value.Value); } + /// + /// #1024: the deploy trigger has its own, longer ask timeout — a cold Roslyn compile on a large fleet can + /// outlast the 10 s used for ack/shelve. A compose slower than the short timeout but inside the deploy one + /// is a normal Accepted, not an OutcomeUnknown. + /// + [Fact] + public async Task Deploy_uses_its_own_longer_timeout_so_a_slow_compose_is_still_Accepted() + { + var gated = new GatedFactory(AclScopeTestDb.Factory($"deploy-longer-{Guid.NewGuid():N}")); + var coordinator = CreateTestProbe("coordinator"); + var actor = Sys.ActorOf(AdminOperationsActor.Props(gated, coordinator.Ref, Enumerable.Empty())); + var registry = new ActorRegistry(); + registry.Register(actor); + var client = new AdminOperationsClient(registry, TimeSpan.FromMilliseconds(300), TimeSpan.FromSeconds(30)); + + gated.Hold(); + var pending = client.StartDeploymentAsync("ci", CancellationToken.None); + await Task.Delay(800, TestContext.Current.CancellationToken); // past the short timeout + pending.IsCompleted.ShouldBeFalse(); + gated.Release(); + + (await pending).Outcome.ShouldBe(StartDeploymentOutcome.Accepted); + } + + /// The production default for the deploy trigger is longer than the general ask timeout. + [Fact] + public void Default_deploy_timeout_exceeds_the_general_ask_timeout() + { + AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThan(AdminOperationsClient.DefaultAskTimeout); + AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(30)); + } + /// A caller-initiated cancellation is still a cancellation, not an unknown outcome. [Fact] public async Task Caller_cancellation_still_throws() diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipLiteralDiagnosticTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipLiteralDiagnosticTests.cs new file mode 100644 index 000000000..59ce2fc2d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipLiteralDiagnosticTests.cs @@ -0,0 +1,29 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; + +/// lmxopcua#1056 — the editor refuses a {{equip}} token in a verbatim/raw/interpolated path literal, as the deploy gate does. +public sealed class EquipLiteralDiagnosticTests +{ + private static readonly ScriptAnalysisService Svc = new(); + + [Theory] + [InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value;", null)] + [InlineData("return ctx.GetTag(\"\"\"{{equip}}/speed\"\"\").Value;", null)] + [InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value is not null;", ScriptAnalysisModes.AlarmPredicate)] + public void A_token_in_a_non_regular_literal_is_an_error_marker_on_its_line(string code, string? mode) + { + var m = Svc.Diagnose(new DiagnoseRequest("var a = 1;\n" + code, Mode: mode), TestContext.Current.CancellationToken).Markers + .Single(x => x.Code == "OTSCRIPT_EQUIPLITERAL"); + m.Severity.ShouldBe(8); + m.StartLineNumber.ShouldBe(2); + m.Message.ShouldContain("regular"); + } + + [Fact] + public void The_regular_literal_form_is_not_flagged_positive_control() + => Svc.Diagnose(new DiagnoseRequest("return ctx.GetTag(\"{{equip}}/speed\").Value;"), TestContext.Current.CancellationToken).Markers + .ShouldNotContain(x => x.Code == "OTSCRIPT_EQUIPLITERAL"); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/PredicateModeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/PredicateModeTests.cs new file mode 100644 index 000000000..8ce36d091 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/PredicateModeTests.cs @@ -0,0 +1,117 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; + +/// +/// lmxopcua#1025 — the editor used to analyse EVERY script as a VirtualTag body (object Run(VirtualTagContext)), +/// but the deploy gate compiles a scripted-alarm predicate as bool Run(AlarmPredicateContext). A predicate +/// returning a non-bool was clean in the editor and refused at deploy. The predicate mode closes that: the editor +/// wraps the source exactly as the gate does, so editor accepts ⇔ publish accepts. +/// +public sealed class PredicateModeTests +{ + private static readonly ScriptAnalysisService Svc = new(); + private static readonly RoslynDeployScriptChecker Gate = new(); + + private static IReadOnlyList Diag(string code, string? mode) => + Svc.Diagnose(new DiagnoseRequest(code, Mode: mode)).Markers; + + [Fact] + public void A_non_bool_return_is_clean_as_a_value_script_but_an_error_as_a_predicate() + { + const string code = """return ctx.GetTag("A").Value;"""; + Diag(code, null).ShouldBeEmpty(); + Diag(code, ScriptAnalysisModes.Value).ShouldBeEmpty(); + var predicate = Diag(code, ScriptAnalysisModes.AlarmPredicate); + predicate.ShouldContain(m => m.Severity == 8); + predicate.First(m => m.Severity == 8).StartLineNumber.ShouldBe(1); + } + + [Fact] + public void A_bool_predicate_is_clean_in_both_modes_positive_control() + { + const string code = """return Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0) > 5;"""; + Diag(code, ScriptAnalysisModes.AlarmPredicate).ShouldBeEmpty(); + Diag(code, ScriptAnalysisModes.Value).ShouldBeEmpty(); + } + + [Fact] + public void Predicate_mode_still_runs_the_sandbox_and_dependency_checks() + { + Diag("""var c = new System.Net.Http.HttpClient(); return true;""", ScriptAnalysisModes.AlarmPredicate) + .ShouldContain(m => m.Severity == 8); + Diag("""var p = "A"; return ctx.GetTag(p).Value is not null;""", ScriptAnalysisModes.AlarmPredicate) + .ShouldContain(m => m.Code == "OTSCRIPT_DYNPATH"); + } + + [Fact] + public void An_unknown_mode_falls_back_to_the_value_shape() + => Diag("""return ctx.GetTag("A").Value;""", "nonsense").ShouldBeEmpty(); + + [Theory] + [InlineData("""return ctx.GetTag("A").Value;""")] + [InlineData("""return 1;""")] + [InlineData("""return true;""")] + [InlineData("""return Convert.ToDouble(ctx.GetTag("A").Value ?? 0.0) > 5;""")] + [InlineData("""var x = ; return true;""")] + [InlineData("""return ctx.Nope();""")] + [InlineData("""return;""")] + [InlineData("""return null;""")] + [InlineData("""var f = new System.IO.FileInfo("/x"); return true;""")] + public void Editor_predicate_verdict_matches_the_deploy_gate(string code) + { + var editorRejects = Diag(code, ScriptAnalysisModes.AlarmPredicate).Any(m => m.Severity == 8); + var gateRejects = !Gate.Check([new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, code)], TestContext.Current.CancellationToken)[0].Passed; + editorRejects.ShouldBe(gateRejects, $"editor/gate disagree on: {code}"); + } + + [Fact] + public void SetVirtualTag_in_a_predicate_is_flagged_as_throwing_not_inert() + { + var markers = Diag("""ctx.SetVirtualTag("X", 1); return true;""", ScriptAnalysisModes.AlarmPredicate); + var m = markers.Single(x => x.Code == "OTSCRIPT_SETVTAG_INERT"); + m.Severity.ShouldBe(4); + m.Message.ShouldContain("throws"); + } + + [Fact] + public async Task Hover_over_ctx_in_predicate_mode_resolves_the_alarm_predicate_context() + { + const string code = "return ctx.GetTag(\"A\").Value is not null;"; + var hover = await Svc.Hover(new HoverRequest(code, 1, 9, Mode: ScriptAnalysisModes.AlarmPredicate), CancellationToken.None); + hover.Markdown.ShouldNotBeNull().ShouldContain("AlarmPredicateContext"); + var valueHover = await Svc.Hover(new HoverRequest(code, 1, 9), CancellationToken.None); + valueHover.Markdown.ShouldNotBeNull().ShouldContain("VirtualTagContext"); + } + + [Fact] + public async Task Completion_in_predicate_mode_offers_ctx_members() + { + var resp = await Svc.CompleteAsync(new CompletionsRequest("return ctx.", 1, 12, Mode: ScriptAnalysisModes.AlarmPredicate), CancellationToken.None); + resp.Items.ShouldContain(i => i.Label == "GetTag"); + } + + [Fact] + public void Predicate_analysis_derives_from_its_own_shared_base_compilation() + { + var c1 = Svc.CompilationFor("return true;", ScriptAnalysisModes.AlarmPredicate); + var c2 = Svc.CompilationFor("return false;", ScriptAnalysisModes.AlarmPredicate); + c1.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object) + .ShouldBeSameAs(c2.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Object)); + } + + [Fact] + public void The_monaco_interop_threads_the_mode_into_every_analysis_request() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx"))) dir = dir.Parent; + var js = File.ReadAllText(Path.Combine(dir!.FullName, "src", "Server", "ZB.MOM.WW.OtOpcUa.AdminUI", "wwwroot", "js", "monaco-init.js")); + js.ShouldContain("__otMode"); + // completions, hover, signature-help and diagnostics each carry it + System.Text.RegularExpressions.Regex.Matches(js, @"mode: modeOf\(model\)").Count.ShouldBeGreaterThanOrEqualTo(4); + js.ShouldContain("setMode"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs new file mode 100644 index 000000000..9747fddce --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/ScriptUsageClassifyTests.cs @@ -0,0 +1,67 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; +using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Acls; +using ZB.MOM.WW.OtOpcUa.AdminUI.Uns; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; + +/// #1025 — the script editor opens in predicate mode only when scripted alarms are the script's sole users. +public sealed class ScriptUsageClassifyTests +{ + private static async Task Classify(Action seed) + { + var factory = AclScopeTestDb.Factory($"script-usage-{Guid.NewGuid():N}"); + await using var db = await factory.CreateDbContextAsync(TestContext.Current.CancellationToken); + seed(db); + await db.SaveChangesAsync(TestContext.Current.CancellationToken); + return await ScriptUsage.ClassifyAsync(db, "s-1", TestContext.Current.CancellationToken); + } + + [Fact] + public async Task An_unused_script_is_a_value_script() + { + var u = await Classify(_ => { }); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.Value); + } + + [Fact] + public async Task A_script_used_only_as_a_predicate_opens_in_predicate_mode() + { + var u = await Classify(db => db.ScriptedAlarms.Add(new ScriptedAlarm + { + ScriptedAlarmId = "al-1", EquipmentId = "eq", Name = "a", AlarmType = "LimitAlarm", MessageTemplate = "m", PredicateScriptId = "s-1", + })); + u.UsedAsPredicate.ShouldBeTrue(); + u.UsedAsValue.ShouldBeFalse(); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.AlarmPredicate); + } + + [Fact] + public async Task A_script_also_used_as_a_virtual_tag_stays_a_value_script() + { + var u = await Classify(db => + { + db.ScriptedAlarms.Add(new ScriptedAlarm + { + ScriptedAlarmId = "al-1", EquipmentId = "eq", Name = "a", AlarmType = "LimitAlarm", MessageTemplate = "m", PredicateScriptId = "s-1", + }); + db.VirtualTags.Add(new VirtualTag { VirtualTagId = "vt-1", EquipmentId = "eq", Name = "v", DataType = "Double", ScriptId = "s-1" }); + }); + u.UsedAsPredicate.ShouldBeTrue(); + u.UsedAsValue.ShouldBeTrue(); + u.DefaultMode.ShouldBe(ScriptAnalysisModes.Value); + } + + [Fact] + public async Task A_calculation_tag_counts_as_a_value_use() + { + var u = await Classify(db => db.Tags.Add(new Tag + { + TagId = "t-1", DeviceId = "d", Name = "calc", DataType = "Double", AccessLevel = ZB.MOM.WW.OtOpcUa.Configuration.Enums.TagAccessLevel.Read, TagConfig = "{\"scriptId\":\"s-1\"}", + })); + u.UsedAsValue.ShouldBeTrue(); + u.UsedAsPredicate.ShouldBeFalse(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs index f6f41bf2e..2688a0599 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs @@ -256,6 +256,48 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct checker.Calls.First().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); } + /// #1024: with warm-on-start the checker is exercised the moment the singleton starts — before any deploy. + [Fact] + public void Warm_on_start_compiles_the_scripts_before_any_deploy_arrives() + { + var checker = new RecordingChecker(); + Sys.ActorOf(AdminOperationsActor.Props( + SeedDraft(new Seed()), CreateTestProbe().Ref, Enumerable.Empty(), + scriptChecker: checker, warmScriptGateOnStart: true)); + + AwaitAssert(() => checker.Calls.Count.ShouldBe(1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + checker.Calls.Single().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); + checker.Calls.Single().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, LegitPredicate)); + } + + /// #1024: warm-on-start is off by default and never runs with the gate Off. + [Fact] + public void Warm_on_start_is_not_run_when_the_gate_is_off_or_not_requested() + { + var checker = new RecordingChecker(); + var db = SeedDraft(new Seed()); + Sys.ActorOf(AdminOperationsActor.Props(db, CreateTestProbe().Ref, Enumerable.Empty(), scriptChecker: checker)); + Sys.ActorOf(AdminOperationsActor.Props(db, CreateTestProbe().Ref, Enumerable.Empty(), + scriptChecker: checker, scriptCompileGateMode: ScriptCompileGateMode.Off, warmScriptGateOnStart: true)); + Thread.Sleep(500); + checker.Calls.ShouldBeEmpty(); + } + + /// #1024: a throwing warm-up never takes the actor down — a deploy still works. + [Fact] + public void A_throwing_start_warm_up_does_not_break_the_next_deploy() + { + var dbFactory = SeedDraft(new Seed()); + var coordinator = CreateTestProbe(); + var checker = new RecordingChecker(@throw: true); + var actor = Sys.ActorOf(AdminOperationsActor.Props( + dbFactory, coordinator.Ref, Enumerable.Empty(), + scriptChecker: checker, scriptCompileGateMode: ScriptCompileGateMode.Warn, warmScriptGateOnStart: true)); + AwaitAssert(() => checker.Calls.Count.ShouldBeGreaterThanOrEqualTo(1), PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + actor.Tell(new StartDeployment("joe", CorrelationId.NewId())); + ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + [Fact] public async Task Collected_uses_resolve_equip_exactly_as_the_compose_seams_do() {