73f49eaf32
#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).
166 lines
8.8 KiB
C#
166 lines
8.8 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
|
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
|
|
|
/// <summary>
|
|
/// The Roslyn implementation of the deploy-time script compile gate (lmxopcua#971 follow-up). For each request it
|
|
/// runs exactly what the runtime seam runs before a script can execute, minus the emit:
|
|
/// <list type="bullet">
|
|
/// <item><b>VirtualTag / Calculation</b> — the passthrough mirror shape (<see cref="PassthroughScript"/>) and a
|
|
/// blank source never reach Roslyn at runtime, so they pass; anything else goes through
|
|
/// <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> as <c>VirtualTagContext → object?</c>.</item>
|
|
/// <item><b>AlarmPredicate</b> — <see cref="DependencyExtractor"/> first (the scripted-alarm load rejects a
|
|
/// non-literal tag path before compiling), then <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> as
|
|
/// <c>AlarmPredicateContext → bool</c>. No passthrough shortcut: the alarm engine always compiles.</item>
|
|
/// </list>
|
|
/// <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> builds its compilation through the same private factory
|
|
/// <see cref="ScriptEvaluator{TContext, TResult}.CompileToImage"/> uses, so the gate and the runtime cannot drift;
|
|
/// which diagnostics refuse and which sources skip the compile are <see cref="ScriptCompileRules"/>, which the Monaco
|
|
/// editor reads too (lmxopcua#1063). One rule is kind-specific and runs before everything else: a
|
|
/// <b>Calculation</b> script may not carry <c>{{equip}}</c> in a path literal
|
|
/// (<see cref="EquipTokenLiteralScanner.FindInCalculation"/>, lmxopcua#1065) — the passthrough shortcut included, and
|
|
/// outside the cache, because VirtualTag and Calculation otherwise share one cached verdict.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// Results are cached by (compile identity, SHA-256 of the source). VirtualTag and Calculation share one
|
|
/// identity — they compile against the same context and result type. The allow-list and the compiler only
|
|
/// change with the binary, so a cached verdict stays valid for the life of the process; the cache is bounded
|
|
/// by <c>capacity</c> (cleared wholesale when full — re-checking is only a cost, never a wrong answer).
|
|
/// Verdicts from an unexpected internal exception are not cached.
|
|
/// </para>
|
|
/// <para>Distinct uncached sources are checked in parallel, bounded by <c>maxParallelism</c>.</para>
|
|
/// </remarks>
|
|
public sealed class RoslynDeployScriptChecker : IDeployScriptChecker
|
|
{
|
|
private readonly ConcurrentDictionary<string, Lazy<CachedVerdict>> _cache = new(StringComparer.Ordinal);
|
|
private readonly int _capacity;
|
|
private readonly int _maxParallelism;
|
|
private long _compiles;
|
|
|
|
/// <summary>Initializes a new instance of the <see cref="RoslynDeployScriptChecker"/> class.</summary>
|
|
/// <param name="capacity">Cached verdicts kept before the cache is cleared; default 4096.</param>
|
|
/// <param name="maxParallelism">Concurrent checks; default half the processors, between 1 and 8.</param>
|
|
public RoslynDeployScriptChecker(int capacity = 4096, int? maxParallelism = null)
|
|
{
|
|
_capacity = Math.Max(1, capacity);
|
|
_maxParallelism = Math.Max(1, maxParallelism ?? Math.Clamp(Environment.ProcessorCount / 2, 1, 8));
|
|
}
|
|
|
|
/// <summary>Gets how many sources this instance has actually run through Roslyn (cache misses).</summary>
|
|
public long CompilesPerformed => Interlocked.Read(ref _compiles);
|
|
|
|
/// <inheritdoc />
|
|
public IReadOnlyList<DeployScriptCheckResult> Check(
|
|
IReadOnlyList<DeployScriptCheckRequest> requests, CancellationToken cancellationToken = default)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(requests);
|
|
var keys = new string?[requests.Count];
|
|
var direct = new IReadOnlyList<string>?[requests.Count];
|
|
var pending = new Dictionary<string, DeployScriptCheckRequest>(StringComparer.Ordinal);
|
|
for (var i = 0; i < requests.Count; i++)
|
|
{
|
|
var request = requests[i] ?? throw new ArgumentException("A request is null.", nameof(requests));
|
|
// lmxopcua#1065: a Calculation script may not carry {{equip}} at all. A source scan, kind-specific, so it runs
|
|
// before the passthrough shortcut (`return ctx.GetTag("{{equip}}/X").Value;` never reaches Roslyn) and outside
|
|
// the compile cache (VirtualTag and Calculation share one cached compile verdict; this rule is not shared).
|
|
if (request.Kind == ScriptContextKind.Calculation
|
|
&& EquipTokenLiteralScanner.FindInCalculation(request.Source) is { Count: > 0 } calcFindings)
|
|
{
|
|
direct[i] = ["equip token in a Calculation script — " + string.Join("; ", calcFindings.Select(f => f.Message))];
|
|
continue;
|
|
}
|
|
if (ScriptCompileRules.SkipsCompile(request.Kind, request.Source)) continue;
|
|
var key = CacheKey(request);
|
|
keys[i] = key;
|
|
if (!_cache.ContainsKey(key)) pending.TryAdd(key, request);
|
|
}
|
|
|
|
if (pending.Count > 0)
|
|
{
|
|
if (_cache.Count + pending.Count > _capacity) _cache.Clear();
|
|
Parallel.ForEach(
|
|
pending,
|
|
new ParallelOptions { MaxDegreeOfParallelism = _maxParallelism, CancellationToken = cancellationToken },
|
|
kv => _ = Resolve(kv.Key, kv.Value));
|
|
}
|
|
|
|
var results = new DeployScriptCheckResult[requests.Count];
|
|
for (var i = 0; i < requests.Count; i++)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
results[i] = new DeployScriptCheckResult(
|
|
requests[i], direct[i] ?? (keys[i] is { } key ? Resolve(key, requests[i]).Problems : []));
|
|
}
|
|
return results;
|
|
}
|
|
|
|
private CachedVerdict Resolve(string key, DeployScriptCheckRequest request)
|
|
{
|
|
var lazy = _cache.GetOrAdd(key, _ => new Lazy<CachedVerdict>(
|
|
() => Run(request), LazyThreadSafetyMode.ExecutionAndPublication));
|
|
var verdict = lazy.Value;
|
|
if (!verdict.Cacheable)
|
|
_cache.TryRemove(new KeyValuePair<string, Lazy<CachedVerdict>>(key, lazy));
|
|
return verdict;
|
|
}
|
|
|
|
private static string CacheKey(DeployScriptCheckRequest request)
|
|
{
|
|
var identity = request.Kind == ScriptContextKind.AlarmPredicate ? "alarm" : "value";
|
|
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(request.Source ?? string.Empty));
|
|
return identity + ":" + Convert.ToHexString(hash);
|
|
}
|
|
|
|
private CachedVerdict Run(DeployScriptCheckRequest request)
|
|
{
|
|
Interlocked.Increment(ref _compiles);
|
|
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);
|
|
if (!extraction.IsValid)
|
|
return new CachedVerdict(
|
|
["dependency extraction rejected — " + string.Join("; ", extraction.Rejections.Select(r => r.Message))],
|
|
Cacheable: true);
|
|
ScriptEvaluator<AlarmPredicateContext, bool>.Verify(source);
|
|
}
|
|
else
|
|
{
|
|
ScriptEvaluator<VirtualTagContext, object?>.Verify(source);
|
|
}
|
|
return new CachedVerdict([], Cacheable: true);
|
|
}
|
|
catch (CompilationErrorException ex)
|
|
{
|
|
return new CachedVerdict(["compile error: " + OneLine(ex.Message)], Cacheable: true);
|
|
}
|
|
catch (ScriptSandboxViolationException ex)
|
|
{
|
|
return new CachedVerdict(["sandbox violation: " + OneLine(ex.Message)], Cacheable: true);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
return new CachedVerdict(["compile failure: " + OneLine(ex.Message)], Cacheable: false);
|
|
}
|
|
}
|
|
|
|
private static string OneLine(string text) =>
|
|
string.Join(" ", text.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()));
|
|
|
|
private sealed record CachedVerdict(IReadOnlyList<string> Problems, bool Cacheable);
|
|
}
|