fix(editor): #1025 analyse scripted-alarm predicates as bool Run(AlarmPredicateContext) — predicate mode on the analysis endpoints, Monaco and the ScriptEdit page
This commit is contained in:
+10
-2
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -152,7 +165,9 @@ public sealed class ScriptAnalysisService
|
||||
// (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 +243,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 +301,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 +421,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 +523,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 };
|
||||
})();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user