Merge scripting follow-ups: deploy gate warm + 45 s deploy ask (#1024), editor predicate mode (#1025), {{equip}} in verbatim/raw/interpolated literal refused (#1056), ScriptRunGuardTests timing cause (#1038), returned sequences materialised + capped (#1059)
This commit is contained in:
+31
-5
@@ -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<AlarmPredicateContext>)` 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<double>`) 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 `<RefName>` 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.)
|
||||
|
||||
---
|
||||
|
||||
|
||||
+2
-2
File diff suppressed because one or more lines are too long
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Finds <c>ctx.GetTag(…)</c> / <c>ctx.SetVirtualTag(…)</c> calls whose path argument carries the
|
||||
/// <c>{{equip}}</c> token in a literal form the substitution does NOT rewrite (lmxopcua#1056).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <c>EquipmentScriptPaths.SubstituteEquipmentToken</c> rewrites the token only inside a REGULAR <c>"…"</c>
|
||||
/// path literal. A verbatim (<c>@"…"</c>), raw (<c>"""…"""</c>) or interpolated (<c>$"…"</c>) 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
|
||||
/// (<c>OTSCRIPT_EQUIPLITERAL</c>) and the deploy gate (<see cref="RoslynDeployScriptChecker"/>) now run this
|
||||
/// one scan and refuse such a script, so "the editor accepts ⇔ publish accepts" holds.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Same receiver guard as <see cref="DependencyExtractor"/> (a member access on the identifier <c>ctx</c>), so
|
||||
/// comments, other receivers and a token in a string that is not a path argument are never flagged.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class EquipTokenLiteralScanner
|
||||
{
|
||||
private const string EquipToken = "{{equip}}";
|
||||
|
||||
/// <summary>One offending path literal.</summary>
|
||||
/// <param name="Span">The offending literal's span in the scanned source.</param>
|
||||
/// <param name="Message">The operator-facing explanation.</param>
|
||||
public sealed record Finding(TextSpan Span, string Message);
|
||||
|
||||
/// <summary>The offending path literals of <paramref name="source"/>, in source order.</summary>
|
||||
/// <param name="source">The script source (any <c>{{equip}}</c> token still unresolved is fine).</param>
|
||||
/// <returns>The findings; empty when none.</returns>
|
||||
public static IReadOnlyList<Finding> 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<Finding>();
|
||||
foreach (var inv in tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>())
|
||||
{
|
||||
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}/<RefName>\")."));
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,12 @@ public static class ForbiddenTypeAnalyzer
|
||||
/// <c>Func<…></c>). A nested type is allowed when its containing type is. Every <c>System.Exception</c>
|
||||
/// subclass declared in the <c>System</c> namespace is allowed in addition to this list.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// lmxopcua#1059: before adding a type here, check its <c>ToString</c> / <c>Equals</c> / <c>GetHashCode</c> for
|
||||
/// recursion over script-built data — the host copies and compares a returned value recursively
|
||||
/// (<c>OwnedDataSample.CopyLegacy</c>, <c>VirtualTagActor.SameValue</c>) 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.
|
||||
/// </remarks>
|
||||
public static readonly IReadOnlyList<string> AllowedTypes =
|
||||
[
|
||||
// Primitives and core value types.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Collections;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
/// <summary>Thrown when a script's returned value is a sequence that is too large, or of a shape the host cannot take (lmxopcua#1059).</summary>
|
||||
public sealed class ScriptResultException : InvalidOperationException
|
||||
{
|
||||
/// <summary>Initializes a new instance of the <see cref="ScriptResultException"/> class.</summary>
|
||||
/// <param name="message">What was wrong with the returned value.</param>
|
||||
public ScriptResultException(string message) : base(message)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Forces a script's returned sequence to be a bounded, concrete value INSIDE the guarded run (lmxopcua#1059).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A script can return an iterator (<c>yield</c>) or an unfinished LINQ query. Nothing has run yet when
|
||||
/// <c>Run</c> returns: the host then enumerates it on ITS thread — outside the guard's timeout and
|
||||
/// allocation sampling, with no bound on the element count — so a <c>while(true) yield return</c> or an
|
||||
/// <c>Enumerable.Range(0, int.MaxValue)</c> would hang or exhaust the publish path rather than the script's own
|
||||
/// run. The guard therefore materialises the result right after the script returns, on the same pool thread, so
|
||||
/// the enumeration is charged to the run (timeout, orphan slot, allocation budget) and is capped at
|
||||
/// <c>maxElements</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// What changes: a lazy sequence (an <see cref="IEnumerable"/> that is neither an array, a string nor an
|
||||
/// <see cref="ICollection"/>) becomes a typed <c>T[]</c> of its <c>IEnumerable<T></c> element type. A
|
||||
/// sequence whose element type could itself be a sequence (<c>object</c>, an interface, another collection) is
|
||||
/// refused — the host copies and compares returned arrays recursively, so an open-slot array can nest or contain
|
||||
/// itself (see <c>ForbiddenTypeAnalyzer</c>). Arrays 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This does NOT make the in-process runner a hard sandbox: memory exhaustion inside the run and a
|
||||
/// non-terminating loop are still only contained by the guard's after-the-fact allocation sample and its timeout
|
||||
/// (an orphaned thread). Only <c>Scripting:Runner=OutOfProcess</c> contains those. See docs/VirtualTags.md.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class ScriptResultMaterializer
|
||||
{
|
||||
/// <summary>Materialises <paramref name="value"/> as described on the type.</summary>
|
||||
/// <param name="value">The script's returned value.</param>
|
||||
/// <param name="maxElements">The element cap; zero or negative disables the cap (a lazy sequence is still materialised, unbounded).</param>
|
||||
/// <returns>The value the host should see.</returns>
|
||||
/// <exception cref="ScriptResultException">The sequence exceeds the cap, or its element type is an open slot.</exception>
|
||||
public static object? Materialize(object? value, int maxElements)
|
||||
{
|
||||
switch (value)
|
||||
{
|
||||
case null or string:
|
||||
return value;
|
||||
case Array array:
|
||||
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<T> 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<object?>();
|
||||
foreach (var item in sequence)
|
||||
{
|
||||
if (maxElements > 0 && items.Count >= maxElements)
|
||||
throw new ScriptResultException(
|
||||
$"The script returned a sequence of more than {maxElements} elements (Scripting:MaxResultElements); " +
|
||||
"it was cut off while being materialised.");
|
||||
items.Add(item);
|
||||
}
|
||||
var result = Array.CreateInstance(elementType, items.Count);
|
||||
for (var i = 0; i < items.Count; i++) result.SetValue(items[i], i);
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void EnforceCap(int count, int maxElements)
|
||||
{
|
||||
if (maxElements > 0 && count > maxElements)
|
||||
throw new ScriptResultException(
|
||||
$"The script returned a collection of {count} elements, over the {maxElements}-element limit (Scripting:MaxResultElements).");
|
||||
}
|
||||
|
||||
private static Type? ElementTypeOf(Type type)
|
||||
{
|
||||
Type? found = null;
|
||||
foreach (var i in type.GetInterfaces().Append(type))
|
||||
{
|
||||
if (!i.IsGenericType || i.GetGenericTypeDefinition() != typeof(IEnumerable<>)) continue;
|
||||
var arg = i.GetGenericArguments()[0];
|
||||
if (found is not null && found != arg) return null; // ambiguous
|
||||
found = arg;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private static bool IsOpenSlot(Type t) =>
|
||||
t == typeof(object) || t.IsInterface || t.IsAbstract
|
||||
|| (t != typeof(string) && typeof(IEnumerable).IsAssignableFrom(t));
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -28,6 +28,9 @@ public sealed class ScriptingOptions
|
||||
/// <summary>Default <see cref="MaxAllocBytesPerRun"/>: 64 MB.</summary>
|
||||
public const long DefaultMaxAllocBytesPerRun = 64L * 1024 * 1024;
|
||||
|
||||
/// <summary>Default <see cref="MaxResultElements"/>: 100 000.</summary>
|
||||
public const int DefaultMaxResultElements = 100_000;
|
||||
|
||||
/// <summary>Default <see cref="QuarantineAfterConsecutiveTimeouts"/>: 3.</summary>
|
||||
public const int DefaultQuarantineAfterConsecutiveTimeouts = 3;
|
||||
|
||||
@@ -53,6 +56,15 @@ public sealed class ScriptingOptions
|
||||
/// </summary>
|
||||
public long MaxAllocBytesPerRun { get; set; } = DefaultMaxAllocBytesPerRun;
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="ScriptResultException"/> past this count. Zero or negative
|
||||
/// becomes the default. Default 100 000.
|
||||
/// </summary>
|
||||
public int MaxResultElements { get; set; } = DefaultMaxResultElements;
|
||||
|
||||
/// <summary>
|
||||
/// 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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -10,28 +10,47 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients;
|
||||
/// <summary>
|
||||
/// <see cref="IAdminOperationsClient"/> backed by the cluster singleton registered in
|
||||
/// <c>AddOtOpcUaControlPlane</c>. Resolves the singleton proxy from <see cref="ActorRegistry"/>
|
||||
/// at construction time; each call <c>Ask</c>s the proxy with a 10s timeout.
|
||||
/// at construction time; each call <c>Ask</c>s the proxy with a 10s timeout (45s for the deploy trigger, #1024).
|
||||
/// </summary>
|
||||
public sealed class AdminOperationsClient : IAdminOperationsClient
|
||||
{
|
||||
private static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10);
|
||||
/// <summary>The general ask timeout (ack / shelve / probes).</summary>
|
||||
internal static readonly TimeSpan DefaultAskTimeout = TimeSpan.FromSeconds(10);
|
||||
|
||||
/// <summary>
|
||||
/// #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
|
||||
/// <see cref="StartDeploymentOutcome.OutcomeUnknown"/>, never a failure — this just makes it rarer.
|
||||
/// </summary>
|
||||
internal static readonly TimeSpan DefaultDeployAskTimeout = TimeSpan.FromSeconds(45);
|
||||
|
||||
private readonly IActorRef _proxy;
|
||||
private readonly TimeSpan AskTimeout;
|
||||
private readonly TimeSpan DeployAskTimeout;
|
||||
|
||||
/// <summary>Initializes a new instance of the AdminOperationsClient.</summary>
|
||||
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
|
||||
public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout)
|
||||
public AdminOperationsClient(ActorRegistry registry) : this(registry, DefaultAskTimeout, DefaultDeployAskTimeout)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the same client with a caller-chosen ask timeout.</summary>
|
||||
/// <summary>Test seam: the same client with a caller-chosen ask timeout (also used for the deploy trigger).</summary>
|
||||
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
|
||||
/// <param name="askTimeout">How long to wait for the singleton's reply.</param>
|
||||
internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout)
|
||||
internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout) : this(registry, askTimeout, askTimeout)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Test seam: caller-chosen general and deploy-trigger ask timeouts.</summary>
|
||||
/// <param name="registry">The actor registry to resolve the admin operations singleton proxy.</param>
|
||||
/// <param name="askTimeout">How long to wait for the singleton's reply to ack/shelve.</param>
|
||||
/// <param name="deployAskTimeout">How long to wait for the singleton's reply to StartDeployment.</param>
|
||||
internal AdminOperationsClient(ActorRegistry registry, TimeSpan askTimeout, TimeSpan deployAskTimeout)
|
||||
{
|
||||
_proxy = registry.Get<AdminOperationsActorKey>();
|
||||
AskTimeout = askTimeout;
|
||||
DeployAskTimeout = deployAskTimeout;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -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<StartDeploymentResult>(msg, AskTimeout, linked.Token);
|
||||
return await _proxy.Ask<StartDeploymentResult>(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);
|
||||
|
||||
@@ -75,8 +75,19 @@ else
|
||||
<section class="panel rise mt-3">
|
||||
<h2 class="panel-head">Source</h2>
|
||||
<div style="padding:1rem">
|
||||
@* #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. *@
|
||||
<div class="mb-2 d-flex align-items-center gap-2">
|
||||
<label class="form-label mb-0" for="@(_fieldId + "-mode")">Analyse as</label>
|
||||
<select id="@(_fieldId + "-mode")" class="form-select form-select-sm w-auto" value="@_mode"
|
||||
@onchange="e => ChangeMode(e.Value?.ToString(), presentation)">
|
||||
<option value="@ScriptAnalysisModes.Value">Virtual tag / Calculation value script</option>
|
||||
<option value="@ScriptAnalysisModes.AlarmPredicate">Scripted-alarm predicate (must return bool)</option>
|
||||
</select>
|
||||
</div>
|
||||
<MonacoEditor @key="presentation" @ref="_editor" Value="@_form.SourceCode" ValueChanged="value => ChangeSource(value, presentation, form)" Height="420px"
|
||||
AriaLabel="Script source code" ReadOnly="@_busy" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
|
||||
AriaLabel="Script source code" ReadOnly="@_busy" Mode="@_mode" MarkersChanged="report => OnMarkersChanged(report, presentation)" />
|
||||
<ScriptProblemsList Report="_markers" OnSelect="marker => RevealProblemAsync(marker, presentation)" />
|
||||
<div class="form-text">SHA-256 hash is computed automatically on save.</div>
|
||||
</div>
|
||||
@@ -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() };
|
||||
|
||||
@@ -53,6 +53,13 @@
|
||||
/// </summary>
|
||||
[Parameter] public string? EquipmentId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Which seam the script is analysed as (<see cref="ScriptAnalysisModes"/>; lmxopcua#1025): null/<c>value</c> for a
|
||||
/// VirtualTag / Calculation script, <c>alarmPredicate</c> for a scripted-alarm predicate (must return <c>bool</c>).
|
||||
/// Changing it re-analyses the live editor.
|
||||
/// </summary>
|
||||
[Parameter] public string? Mode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>ScriptProblemsList</c>; 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;
|
||||
|
||||
@@ -1,22 +1,43 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <c>object Run(ScriptGlobals<VirtualTagContext>)</c> (VirtualTag and Calculation share it); a scripted-alarm
|
||||
/// predicate is <c>bool Run(ScriptGlobals<AlarmPredicateContext>)</c>. Carried as a string on the wire; null,
|
||||
/// blank or anything unrecognised means <see cref="Value"/>.
|
||||
/// </summary>
|
||||
public static class ScriptAnalysisModes
|
||||
{
|
||||
/// <summary>A VirtualTag / Calculation value script (the default).</summary>
|
||||
public const string Value = "value";
|
||||
|
||||
/// <summary>A scripted-alarm predicate: must return <c>bool</c>.</summary>
|
||||
public const string AlarmPredicate = "alarmPredicate";
|
||||
|
||||
/// <summary>True when <paramref name="mode"/> selects the predicate shape.</summary>
|
||||
/// <param name="mode">The wire value.</param>
|
||||
/// <returns>Whether it names <see cref="AlarmPredicate"/>.</returns>
|
||||
public static bool IsPredicate(string? mode) => string.Equals(mode, AlarmPredicate, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
// EquipmentId (optional) carries the owning-equipment context the {{equip}}/<RefName> 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<DiagnosticMarker> 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<CompletionItem> 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<SignatureHelpParameter>? Parameters, int ActiveParameter);
|
||||
public record SignatureHelpParameter(string Label, string? Documentation);
|
||||
|
||||
|
||||
@@ -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;
|
||||
/// </remarks>
|
||||
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<VirtualTagContext>) 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<global::{typeof(VirtualTagContext).FullName}>";
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// The process-wide compilation every analysis derives from. Its sandbox reference set is bound ONCE
|
||||
/// (forced here by resolving <c>System.Object</c>); <see cref="CSharpCompilation.ReplaceSyntaxTree"/> 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 <see cref="BaseCompilation"/> every analysis of that seam derives from. Its sandbox reference
|
||||
/// set is bound ONCE (forced by resolving <c>System.Object</c>); <see cref="CSharpCompilation.ReplaceSyntaxTree"/>
|
||||
/// keeps that binding, so a request only re-binds the user's tree. Immutable, so shared across circuits/requests.
|
||||
/// </summary>
|
||||
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<TContext>)
|
||||
// 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<global::{contextType.FullName}>";
|
||||
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;
|
||||
|
||||
/// <summary>The process-wide value-shape compilation (test seam; the predicate shape has its own).</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the compilation one analysis of <paramref name="userSource"/> runs against.</summary>
|
||||
internal CSharpCompilation CompilationFor(string userSource) => Analyze(Normalize(userSource), CancellationToken.None).Compilation;
|
||||
/// <param name="userSource">The script source.</param>
|
||||
/// <param name="mode">The analysis mode (<see cref="ScriptAnalysisModes"/>); null = value.</param>
|
||||
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<DiagnosticMarker>();
|
||||
|
||||
// (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));
|
||||
|
||||
|
||||
@@ -21,6 +21,42 @@ public static class ScriptUsage
|
||||
/// <summary>How many using rows are named in the refusal before it summarises the rest.</summary>
|
||||
private const int NamedLimit = 5;
|
||||
|
||||
/// <summary>Which seams use a script.</summary>
|
||||
/// <param name="UsedAsValue">An (any) VirtualTag or Calculation tag runs it as a value script.</param>
|
||||
/// <param name="UsedAsPredicate">An (any) scripted alarm runs it as its predicate.</param>
|
||||
public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate)
|
||||
{
|
||||
/// <summary>
|
||||
/// The editor analysis mode (<c>ScriptAnalysisModes</c>) 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.
|
||||
/// </summary>
|
||||
public string DefaultMode =>
|
||||
UsedAsPredicate && !UsedAsValue ? ScriptAnalysis.ScriptAnalysisModes.AlarmPredicate : ScriptAnalysis.ScriptAnalysisModes.Value;
|
||||
}
|
||||
|
||||
/// <summary>Classifies which seams use <paramref name="scriptId"/> (same rows, same Calculation parser as the delete check).</summary>
|
||||
/// <param name="db">The config context.</param>
|
||||
/// <param name="scriptId">The script.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>Where the script is used.</returns>
|
||||
public static async Task<SeamUsage> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Describes every row that references <paramref name="scriptId"/>, or returns <see langword="null"/> when
|
||||
/// nothing does and the script may be deleted.
|
||||
|
||||
@@ -52,6 +52,9 @@
|
||||
// registered csharp providers (which only receive the model) can thread it into the {{equip}}/<RefName>
|
||||
// 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}}/<RefName> 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 };
|
||||
})();
|
||||
|
||||
@@ -33,6 +33,8 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
|
||||
private readonly ScriptCompileGateMode _scriptCompileGateMode;
|
||||
|
||||
private readonly bool _warmScriptGateOnStart;
|
||||
|
||||
/// <summary>
|
||||
/// The coordinator's apply deadline. A <c>Dispatching</c> 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
|
||||
/// <param name="alarmVerdictWindow">#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts; defaults to <see cref="AlarmCommandVerdictCollector.DefaultWindow"/>.</param>
|
||||
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
|
||||
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
|
||||
/// <param name="warmScriptGateOnStart">#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.</param>
|
||||
/// <returns>Props configured to create an AdminOperationsActor.</returns>
|
||||
public static Props Props(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> 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));
|
||||
|
||||
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
|
||||
/// <param name="dbFactory">Factory for creating config database contexts.</param>
|
||||
@@ -91,6 +95,7 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
/// <param name="alarmVerdictWindow">#950: the <c>/alerts</c> verdict collection window.</param>
|
||||
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
|
||||
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
|
||||
/// <param name="warmScriptGateOnStart">#1024: warm the checker's cache in the background on start.</param>
|
||||
public AdminOperationsActor(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> 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<ShelveAlarmCommand>(HandleShelveAlarm);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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).
|
||||
/// </summary>
|
||||
protected override void PreStart()
|
||||
{
|
||||
base.PreStart();
|
||||
if (_warmScriptGateOnStart && _scriptChecker is { } checker)
|
||||
_ = Task.Run(() => WarmScriptCompileGateAsync(checker));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The reply text for an unexpected server-side failure (R03:4.1): a fixed sentence plus the request's
|
||||
/// correlation id, never <c>ex.Message</c> — a SqlException or UriFormatException message carries
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1056 — <c>{{equip}}/<RefName></c> is only substituted inside a REGULAR <c>"…"</c> path literal. In a
|
||||
/// verbatim (<c>@"…"</c>), raw (<c>"""…"""</c>) or interpolated (<c>$"…"</c>) 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 (<c>OTSCRIPT_EQUIPLITERAL</c>) and the deploy gate both refuse them.
|
||||
/// </summary>
|
||||
[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<string, string> { ["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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1059 — a script that returns an iterator or an unfinished LINQ query used to hand the host a sequence
|
||||
/// nothing had run yet; the host then enumerated it on its own thread, outside the guard's timeout / allocation sample
|
||||
/// and with no element bound. The guard now materialises the result inside the guarded run, bounded.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class ScriptResultMaterializerTests
|
||||
{
|
||||
private static IEnumerable<double> Endless() { var i = 0.0; while (true) yield return i++; }
|
||||
|
||||
[Fact]
|
||||
public void A_lazy_sequence_becomes_a_typed_array_and_runs_now()
|
||||
{
|
||||
var ran = 0;
|
||||
var lazy = Enumerable.Range(0, 4).Select(i => { ran++; return (double)i; });
|
||||
ran.ShouldBe(0);
|
||||
|
||||
var result = ScriptResultMaterializer.Materialize(lazy, 100).ShouldBeOfType<double[]>();
|
||||
|
||||
result.ShouldBe([0.0, 1.0, 2.0, 3.0]);
|
||||
ran.ShouldBe(4);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_sequence_past_the_cap_is_cut_off_not_enumerated_forever()
|
||||
{
|
||||
var ex = Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Endless(), 1000));
|
||||
ex.Message.ShouldContain("1000");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_sequence_of_exactly_the_cap_is_accepted_boundary()
|
||||
=> ScriptResultMaterializer.Materialize(Enumerable.Range(0, 5).Select(i => (long)i), 5)
|
||||
.ShouldBeOfType<long[]>().Length.ShouldBe(5);
|
||||
|
||||
[Fact]
|
||||
public void A_lazy_sequence_of_an_open_slot_type_is_refused()
|
||||
{
|
||||
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (object)i), 100));
|
||||
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => new List<int> { i }), 100));
|
||||
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => (IComparable)i), 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Arrays_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<int> { 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<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new double[101], 100));
|
||||
Should.Throw<ScriptResultException>(() => ScriptResultMaterializer.Materialize(new List<int>(new int[101]), 100));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_zero_cap_disables_the_bound_but_still_materialises()
|
||||
=> ScriptResultMaterializer.Materialize(Enumerable.Range(0, 3).Select(i => i), 0).ShouldBeOfType<int[]>();
|
||||
|
||||
[Fact]
|
||||
public void The_options_clamp_a_non_positive_cap_to_the_default()
|
||||
{
|
||||
var sanitized = new ScriptingOptions { MaxResultElements = 0 }.Sanitized(out var notes);
|
||||
sanitized.MaxResultElements.ShouldBe(ScriptingOptions.DefaultMaxResultElements);
|
||||
notes.ShouldContain(n => n.Contains("MaxResultElements"));
|
||||
new ScriptingOptions().Sanitized(out var none).MaxResultElements.ShouldBe(ScriptingOptions.DefaultMaxResultElements);
|
||||
none.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
// ---- through the guard, with a real compiled script ----
|
||||
|
||||
private static ScriptEvaluator<FakeScriptContext, object?> Compile(string source) =>
|
||||
ScriptEvaluator<FakeScriptContext, object?>.Compile(source);
|
||||
|
||||
[Fact]
|
||||
public async Task The_guard_hands_the_host_a_materialised_array_not_a_live_query()
|
||||
{
|
||||
var guard = new ScriptRunGuard();
|
||||
using var eval = Compile("return System.Linq.Enumerable.Range(0, 3).Select(i => (double)i * 2);");
|
||||
var result = await guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
|
||||
result.ShouldBeOfType<double[]>().ShouldBe([0.0, 2.0, 4.0]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_guard_cuts_off_an_endless_lazy_sequence_inside_the_run_and_does_not_strike_the_script()
|
||||
{
|
||||
var guard = new ScriptRunGuard(new ScriptingOptions { MaxResultElements = 1000, QuarantineAfterConsecutiveTimeouts = 1 });
|
||||
using var eval = Compile("return System.Linq.Enumerable.Range(0, int.MaxValue).Select(i => (double)i);");
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
|
||||
await Should.ThrowAsync<ScriptResultException>(() => guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), ct));
|
||||
await Should.ThrowAsync<ScriptResultException>(() => guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), ct));
|
||||
guard.IsQuarantined("k", out _).ShouldBeFalse("a refused result is a failed run, not a timeout strike");
|
||||
guard.InFlightCount.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_guard_charges_the_enumeration_to_the_allocation_budget()
|
||||
{
|
||||
// 2 MB budget; the sequence materialises ~100k strings — the allocation happens during enumeration, which used to
|
||||
// be outside the sample entirely.
|
||||
var guard = new ScriptRunGuard(new ScriptingOptions { MaxAllocBytesPerRun = 1024 * 1024 });
|
||||
using var eval = Compile("return System.Linq.Enumerable.Range(0, 90000).Select(i => new string('x', 64) + i);");
|
||||
await Should.ThrowAsync<ScriptQuarantinedException>(() =>
|
||||
guard.RunAsync("k", "src", eval, new FakeScriptContext(), TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
|
||||
guard.IsQuarantined("k", out var reason).ShouldBeTrue();
|
||||
reason!.ShouldContain("allocated");
|
||||
}
|
||||
}
|
||||
@@ -310,41 +310,41 @@ public sealed class ScriptRunGuardTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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
|
||||
/// <see cref="BriefSpinScript"/>), 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.
|
||||
/// </remarks>
|
||||
[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<ScriptTimeoutException>(() => Run(guard, "k", BriefSpinScript, spin, timeout, ct, held));
|
||||
// …so the very next trigger is deterministically refused while it is young.
|
||||
await Should.ThrowAsync<ScriptRunRefusedException>(() => 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<ScriptTimeoutException>(() => guard.RunAsync("k", source, eval, Ctx(200), timeout, ct));
|
||||
await Should.ThrowAsync<ScriptRunRefusedException>(() => 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);
|
||||
}
|
||||
|
||||
|
||||
+32
@@ -65,6 +65,38 @@ public sealed class AdminOperationsClientDeployTimeoutTests : TestKit
|
||||
.DeploymentId.ShouldBe(result.DeploymentId.Value.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #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.
|
||||
/// </summary>
|
||||
[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<IDriverProbe>()));
|
||||
var registry = new ActorRegistry();
|
||||
registry.Register<AdminOperationsActorKey>(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);
|
||||
}
|
||||
|
||||
/// <summary>The production default for the deploy trigger is longer than the general ask timeout.</summary>
|
||||
[Fact]
|
||||
public void Default_deploy_timeout_exceeds_the_general_ask_timeout()
|
||||
{
|
||||
AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThan(AdminOperationsClient.DefaultAskTimeout);
|
||||
AdminOperationsClient.DefaultDeployAskTimeout.ShouldBeGreaterThanOrEqualTo(TimeSpan.FromSeconds(30));
|
||||
}
|
||||
|
||||
/// <summary>A caller-initiated cancellation is still a cancellation, not an unknown outcome.</summary>
|
||||
[Fact]
|
||||
public async Task Caller_cancellation_still_throws()
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
|
||||
|
||||
/// <summary>lmxopcua#1056 — the editor refuses a <c>{{equip}}</c> token in a verbatim/raw/interpolated path literal, as the deploy gate does.</summary>
|
||||
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");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1025 — the editor used to analyse EVERY script as a VirtualTag body (<c>object Run(VirtualTagContext)</c>),
|
||||
/// but the deploy gate compiles a scripted-alarm predicate as <c>bool Run(AlarmPredicateContext)</c>. 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.
|
||||
/// </summary>
|
||||
public sealed class PredicateModeTests
|
||||
{
|
||||
private static readonly ScriptAnalysisService Svc = new();
|
||||
private static readonly RoslynDeployScriptChecker Gate = new();
|
||||
|
||||
private static IReadOnlyList<DiagnosticMarker> 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");
|
||||
}
|
||||
}
|
||||
+67
@@ -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;
|
||||
|
||||
/// <summary>#1025 — the script editor opens in predicate mode only when scripted alarms are the script's sole users.</summary>
|
||||
public sealed class ScriptUsageClassifyTests
|
||||
{
|
||||
private static async Task<ScriptUsage.SeamUsage> Classify(Action<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> 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();
|
||||
}
|
||||
}
|
||||
+42
@@ -256,6 +256,48 @@ public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneAct
|
||||
checker.Calls.First().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit));
|
||||
}
|
||||
|
||||
/// <summary>#1024: with warm-on-start the checker is exercised the moment the singleton starts — before any deploy.</summary>
|
||||
[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<IDriverProbe>(),
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>#1024: warm-on-start is off by default and never runs with the gate Off.</summary>
|
||||
[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<IDriverProbe>(), scriptChecker: checker));
|
||||
Sys.ActorOf(AdminOperationsActor.Props(db, CreateTestProbe().Ref, Enumerable.Empty<IDriverProbe>(),
|
||||
scriptChecker: checker, scriptCompileGateMode: ScriptCompileGateMode.Off, warmScriptGateOnStart: true));
|
||||
Thread.Sleep(500);
|
||||
checker.Calls.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>#1024: a throwing warm-up never takes the actor down — a deploy still works.</summary>
|
||||
[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<IDriverProbe>(),
|
||||
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<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Collected_uses_resolve_equip_exactly_as_the_compose_seams_do()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user