156 lines
7.8 KiB
C#
156 lines
7.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.
|
|
/// </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 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));
|
|
if (SkipsCompile(request)) 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], 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;
|
|
}
|
|
|
|
/// <summary>True when the runtime seam answers the source without compiling it.</summary>
|
|
private static bool SkipsCompile(DeployScriptCheckRequest request) =>
|
|
request.Kind is ScriptContextKind.VirtualTag or ScriptContextKind.Calculation
|
|
&& (string.IsNullOrWhiteSpace(request.Source) || PassthroughScript.TryMatch(request.Source, out _));
|
|
|
|
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);
|
|
}
|