Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs
T
Joseph Doherty 73f49eaf32 fix(scripting): #1063 one compile-refusal authority for editor and deploy gate (ScriptCompileRules + the runtime's own wrapper text) — CS0161 and wrapper injection are now flagged in the editor; #1065 {{equip}} in a Calculation script is refused by the gate and by a new Calculation editor mode
#1063: the Monaco diagnostics dropped every Roslyn error located in the synthesized
wrapper as 'phantom', so CS0161 (not all code paths return a value, pinned on Run)
passed the editor and failed the deploy gate. ScriptCompileRules (Core.Scripting) now
states which diagnostics refuse (every Error, wherever located; LMX001/002 injection)
and which sources skip the compile (blank/passthrough value scripts); ScriptEvaluator
and the editor both use it, and the editor wraps with ScriptEvaluator.WrapperPreamble/
WrapperSuffix instead of its own copy. Wrapper-located refusals are drawn on the
script's last line. EditorGateParityTests runs one corpus through editor and gate in
all three modes.

#1065: a Calculation tag is raw/device-level with no equipment and its seam never
substitutes {{equip}}, so such a script deployed clean and read Bad forever. Refused
rather than substituted: EquipTokenLiteralScanner.FindInCalculation is run by
RoslynDeployScriptChecker for every Calculation use (before the passthrough shortcut,
outside the shared VT/Calc cache) and by the editor in the new 'calculation' mode
(Calculation tag editor; ScriptEdit defaults to it when a Calculation tag uses the
script).
2026-12-03 16:47:14 -05:00

111 lines
6.4 KiB
C#

using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
/// <summary>
/// The script-delete usage check (lmxopcua#978, review C-2). <c>VirtualTag.ScriptId</c>,
/// <c>ScriptedAlarm.PredicateScriptId</c> and a Calculation tag's <c>TagConfig.scriptId</c> carry no FK, so
/// a delete used to succeed against a script in use; the next deploy then silently dropped the scripted alarm
/// (and deployed the VirtualTag with an empty expression). The deploy gate now refuses such a draft
/// (<c>VirtualTagScriptNotFound</c> / <c>ScriptedAlarmScriptNotFound</c> / <c>CalculationScriptNotFound</c>);
/// this stops the delete that would create it, and says which rows hold the script.
/// </summary>
/// <remarks>
/// A check-then-delete is not serialised against a concurrent "bind a VirtualTag to this script" — the deploy
/// gate is the backstop for that window. A real FK (<c>Restrict</c>) would close it but needs a migration.
/// </remarks>
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>
/// <param name="UsedAsCalculation">An (any) Calculation tag runs it (implies <paramref name="UsedAsValue"/>).</param>
public readonly record struct SeamUsage(bool UsedAsValue, bool UsedAsPredicate, bool UsedAsCalculation = false)
{
/// <summary>
/// The editor analysis mode (<c>ScriptAnalysisModes</c>) a script should open in (lmxopcua#1025): Calculation mode
/// whenever a Calculation tag runs it (lmxopcua#1065 — the deploy gate refuses <c>{{equip}}</c> for that use, and
/// Calculation mode is the value shape plus exactly that rule, so it is the mode that shows every refusal a value
/// use can meet); the predicate shape only when scripted alarms are its sole users; otherwise — also run as a
/// virtual tag, or unused — a value script. The author can switch.
/// </summary>
public string DefaultMode =>
UsedAsCalculation ? ScriptAnalysis.ScriptAnalysisModes.Calculation
: 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 virtualTag = await db.VirtualTags.AsNoTracking().AnyAsync(v => v.ScriptId == scriptId, ct);
var calcCandidates = await db.Tags.AsNoTracking()
.Where(t => t.TagConfig.Contains(scriptId))
.Select(t => t.TagConfig)
.ToListAsync(ct);
var calculation = calcCandidates.Any(c => string.Equals(DraftValidator.ParseScriptId(c), scriptId, StringComparison.Ordinal));
return new SeamUsage(virtualTag || calculation, predicate, calculation);
}
/// <summary>
/// Describes every row that references <paramref name="scriptId"/>, or returns <see langword="null"/> when
/// nothing does and the script may be deleted.
/// </summary>
/// <param name="db">The context the delete will run on.</param>
/// <param name="scriptId">The script about to be deleted.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A refusal naming the users, or <see langword="null"/> when the script is unused.</returns>
public static async Task<string?> DescribeBlockingUsageAsync(
OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentException.ThrowIfNullOrEmpty(scriptId);
var users = new List<string>();
var vtags = await db.VirtualTags.AsNoTracking()
.Where(v => v.ScriptId == scriptId)
.OrderBy(v => v.VirtualTagId)
.Select(v => new { v.VirtualTagId, v.Name, v.EquipmentId })
.ToListAsync(ct);
users.AddRange(vtags.Select(v => $"virtual tag '{v.Name}' ({v.VirtualTagId}) on equipment {v.EquipmentId}"));
var alarms = await db.ScriptedAlarms.AsNoTracking()
.Where(a => a.PredicateScriptId == scriptId)
.OrderBy(a => a.ScriptedAlarmId)
.Select(a => new { a.ScriptedAlarmId, a.Name, a.EquipmentId })
.ToListAsync(ct);
users.AddRange(alarms.Select(a => $"scripted alarm '{a.Name}' ({a.ScriptedAlarmId}) on equipment {a.EquipmentId}"));
// Calculation tags hold the id inside schemaless JSON: narrow in SQL by substring, then confirm with the
// same parser the deploy gate uses, so a script id that merely appears in another key never blocks.
var calcCandidates = await db.Tags.AsNoTracking()
.Where(t => t.TagConfig.Contains(scriptId))
.OrderBy(t => t.TagId)
.Select(t => new { t.TagId, t.Name, t.TagConfig })
.ToListAsync(ct);
users.AddRange(calcCandidates
.Where(t => string.Equals(DraftValidator.ParseScriptId(t.TagConfig), scriptId, StringComparison.Ordinal))
.Select(t => $"calculation tag '{t.Name}' ({t.TagId})"));
if (users.Count == 0) return null;
var named = string.Join("; ", users.Take(NamedLimit));
var more = users.Count > NamedLimit ? $"; and {users.Count - NamedLimit} more" : string.Empty;
return $"This script is still used by {users.Count} item(s): {named}{more}. "
+ "Point them at another script or delete them first — a deployment would reject them otherwise.";
}
}