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;
///
/// 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:
///
/// - VirtualTag / Calculation — the passthrough mirror shape () and a
/// blank source never reach Roslyn at runtime, so they pass; anything else goes through
/// as VirtualTagContext → object?.
/// - AlarmPredicate — first (the scripted-alarm load rejects a
/// non-literal tag path before compiling), then as
/// AlarmPredicateContext → bool. No passthrough shortcut: the alarm engine always compiles.
///
/// builds its compilation through the same private factory
/// uses, so the gate and the runtime cannot drift;
/// which diagnostics refuse and which sources skip the compile are , which the Monaco
/// editor reads too (lmxopcua#1063). One rule is kind-specific and runs before everything else: a
/// Calculation script may not carry {{equip}} in a path literal
/// (, lmxopcua#1065) — the passthrough shortcut included, and
/// outside the cache, because VirtualTag and Calculation otherwise share one cached verdict.
///
///
///
/// 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 capacity (cleared wholesale when full — re-checking is only a cost, never a wrong answer).
/// Verdicts from an unexpected internal exception are not cached.
///
/// Distinct uncached sources are checked in parallel, bounded by maxParallelism.
///
public sealed class RoslynDeployScriptChecker : IDeployScriptChecker
{
private readonly ConcurrentDictionary> _cache = new(StringComparer.Ordinal);
private readonly int _capacity;
private readonly int _maxParallelism;
private long _compiles;
/// Initializes a new instance of the class.
/// Cached verdicts kept before the cache is cleared; default 4096.
/// Concurrent checks; default half the processors, between 1 and 8.
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));
}
/// Gets how many sources this instance has actually run through Roslyn (cache misses).
public long CompilesPerformed => Interlocked.Read(ref _compiles);
///
public IReadOnlyList Check(
IReadOnlyList requests, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(requests);
var keys = new string?[requests.Count];
var direct = new IReadOnlyList?[requests.Count];
var pending = new Dictionary(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(
() => Run(request), LazyThreadSafetyMode.ExecutionAndPublication));
var verdict = lazy.Value;
if (!verdict.Cacheable)
_cache.TryRemove(new KeyValuePair>(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.Verify(source);
}
else
{
ScriptEvaluator.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 Problems, bool Cacheable);
}