Merge #971 follow-up: deploy-time script compile gate (allow-list refusals block the deploy, Error mode default)
This commit is contained in:
@@ -400,6 +400,7 @@ exactly. The backend lives in
|
||||
endpoints under `/api/script-analysis/*`, gated by the `ConfigEditor` policy
|
||||
(Administrator or Designer) via `RequireAuthorization` in
|
||||
`ScriptAnalysisEndpoints.MapScriptAnalysisEndpoints`).
|
||||
**The deploy gate compiles scripts too** (lmxopcua#971 follow-up): `AdminOperationsActor` runs every in-use script (enabled VirtualTags / scripted-alarm predicates / Calculation tags, `{{equip}}` resolved) through `IDeployScriptChecker` (Roslyn impl bound by the Host; ControlPlane stays Roslyn-free) — `Deployment:ScriptCompileGateMode` = `Error` (default, rejects `ScriptCompileFailed`) | `Warn` | `Off`. See `docs/VirtualTags.md` §"Deploy-time script compile gate".
|
||||
`Core.VirtualTags` is now just `DependencyGraph`, `ITagUpstreamSource` and `IHistoryWriter` — the dormant `VirtualTagEngine`/Source/Definition and `TimerTriggerScheduler` were deleted.
|
||||
See `docs/ScriptEditor.md` for the full guide. Scripts may use the `{{equip}}` token for equipment-relative tag paths that resolve per-equipment at deploy time — see the "Equipment-relative tag paths" section in `docs/ScriptEditor.md`.
|
||||
|
||||
|
||||
@@ -178,6 +178,22 @@ editor ⇔ publish parity (`Editor_and_publish_gate_agree`). Each violation is
|
||||
mapped via `tree.GetMappedLineSpan(span)` to user-source coordinates and emitted
|
||||
as an error marker with code `OTSCRIPT_FORBIDDEN`.
|
||||
|
||||
### The deploy gate compiles too (lmxopcua#971 follow-up)
|
||||
|
||||
Saving a script is not compile-gated — the editor's diagnostics are advisory while
|
||||
you type. The **deploy** is: before a deployment is sealed, every script it will
|
||||
run (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags) is
|
||||
compiled through the same `ScriptEvaluator` pipeline the runtime uses, with
|
||||
`{{equip}}/<RefName>` already resolved per equipment exactly as the compose seams
|
||||
resolve it. Under the default `Deployment:ScriptCompileGateMode=Error`, a script
|
||||
the runtime would refuse rejects the deploy with `ScriptCompileFailed`, naming the
|
||||
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`
|
||||
§"Deploy-time script compile gate" for modes, caching and the upgrade note.
|
||||
|
||||
### Runtime safety (what happens after publish)
|
||||
|
||||
The editor cannot catch a script that compiles cleanly but never returns or
|
||||
|
||||
+18
-1
@@ -48,7 +48,24 @@ The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type a
|
||||
|
||||
**Adding to the list.** Add a type only if it has no I/O, no process-wide state, no background work, no blocking wait, and no member that returns or accepts a reflection handle; prefer a new `ScriptContext` helper to opening BCL surface. The editor's completions, diagnostics and the publish gate all follow the list automatically (one authority).
|
||||
|
||||
**Upgrading.** A deployed script that used an API now off the list (the 2026-12 differential over every script in the repo found none apart from an expression-tree test) is refused when the upgraded node compiles it (the deploy gate does not compile scripts): a virtual tag or Calculation tag publishes Bad with `sandbox violation: …` and a Warning log line, and a scripted alarm's predicate fails to load. Re-run the analyzer over stored scripts before upgrading — open each in the script editor (same analyzer), or compile them through `ScriptEvaluator`.
|
||||
**Upgrading.** A deployed script that used an API now off the list (the 2026-12 differential over every script in the repo found none apart from an expression-tree test) is refused when the upgraded node compiles it: a virtual tag or Calculation tag publishes Bad with `sandbox violation: …` and a Warning log line, and a scripted alarm's predicate fails to load — which fails the **whole** scripted-alarm load on that node. Nodes recompile the running artifact on restart, so this happens on upgrade regardless of the deploy gate. What changes with the [deploy-time compile gate](#deploy-time-script-compile-gate-deploymentscriptcompilegatemode) is the **next deploy**: in its default `Error` mode it is rejected, naming each refused script and the entities that use it. Fix the script, disable the using VirtualTag / scripted alarm, or set `Deployment:ScriptCompileGateMode=Warn` to deploy anyway. To find them before upgrading, open each stored script in the script editor (same analyzer).
|
||||
|
||||
### Deploy-time script compile gate (`Deployment:ScriptCompileGateMode`)
|
||||
|
||||
The deploy gate compiles every script the deployment will run before the deployment is sealed (lmxopcua#971 follow-up), so **editor rejects ⇔ publish rejects** holds for deploys too — before this, `DraftValidator` never compiled a script, and a refused script surfaced only as a Bad tag or a failed alarm load after the deploy.
|
||||
|
||||
- **What is checked** is what runs: **enabled** VirtualTags (as `VirtualTagContext → object?`), **enabled** scripted-alarm predicates (`DependencyExtractor` first, as the alarm load does, then `AlarmPredicateContext → bool`), and Calculation tags of **enabled** Calculation drivers (`VirtualTagContext → object?`). Disabled ones are skipped (they never compile at runtime); a passthrough mirror VirtualTag/Calculation body is skipped (the runtime never compiles it); orphan scripts are not checked. The same source can fail as one seam and pass as another — `return 1.5;` is a fine VirtualTag and a refused predicate.
|
||||
- **`{{equip}}` is resolved first**, through the same `EquipmentReferenceMap` + RawPath resolver both compose seams use. When `EquipmentScriptPaths.SubstitutionPreservesCompilation` proves the substitution only rewrites escape-free string-literal text (it cannot change a compile), the template is compiled once for every equipment instead of once per equipment; otherwise the resolved source is compiled. That fallback is not theoretical: a RawPath segment may contain `\` or `"`, and substitution pastes it into a C# literal unescaped, so `{{equip}}/speed` over a device named `de\qv` does not compile — the gate reports it.
|
||||
- **Same compile as the runtime.** `ScriptEvaluator.Verify` and `CompileToImage` share one private factory (wrap, injection guard, sandbox compile, `ForbiddenTypeAnalyzer`); `Verify` stops before the stack-guard rewrite and the emit. Problems carry the runtime's own text (`compile error: …`, `sandbox violation: …`, `dependency extraction rejected — …`).
|
||||
- **Shape.** ControlPlane (which owns the gate) is Roslyn-free: it depends on `IDeployScriptChecker` (`Core.Scripting.Abstractions`); the Host binds `RoslynDeployScriptChecker` on admin nodes. No checker registered ⇒ the gate is skipped. Verdicts are cached by (compile identity, source SHA-256) for the life of the process (VirtualTag and Calculation share an identity), and distinct uncached sources compile in parallel (half the cores, 1–8). The compose warms that cache from the `Script`/`VirtualTag`/`ScriptedAlarm` tables **before** opening its snapshot transaction and compose lock, then runs the authoritative check on the same snapshot it validates and composes (R03:3.2) — normally all cache hits. An internal checker failure skips the gate for that deploy (logged, noted in the accepted message), never blocks it.
|
||||
|
||||
| `Deployment:ScriptCompileGateMode` | Behaviour |
|
||||
|---|---|
|
||||
| `Error` (default) | A refused script is a `ScriptCompileFailed` reject, one per (script, seam, problem), naming the script, the seam and up to five using entities (`+N more`). |
|
||||
| `Warn` | Logged and appended to the accepted deployment message; the deploy succeeds. |
|
||||
| `Off` | The gate does not run. |
|
||||
|
||||
Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the AdminUI waits 10 s for a deploy answer, so on a very large fleet the first deploy after a restart can report a timeout while it carries on — the next is cached.
|
||||
|
||||
|
||||
#### Known resource limits (accepted trade-offs)
|
||||
|
||||
@@ -1947,6 +1947,18 @@ reflection handle can be reached. `ScriptSandbox` compiles against eight BCL ass
|
||||
not even bind. The publish gate and the script editor share both, so the editor shows exactly what publish refuses.
|
||||
Full list and rules: `docs/VirtualTags.md` §"The sandbox is an allow-list".
|
||||
|
||||
**The deploy gate enforces it before a deployment ships** (lmxopcua#971 follow-up). Every script a deployment will
|
||||
run — enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags — is compiled through the same
|
||||
pipeline and analyzer on the central node (`IDeployScriptChecker`, bound by the Host on admin nodes; compile only,
|
||||
nothing is emitted or loaded there) with `{{equip}}` already resolved. `Deployment:ScriptCompileGateMode` defaults
|
||||
to **`Error`**: a script the allow-list refuses rejects the deploy (`ScriptCompileFailed`, naming the script and its
|
||||
users) instead of reaching nodes. This is not a second security boundary — the runtime compile on each node remains
|
||||
the enforcement point, and a refused script never runs either way — but it makes a sandbox refusal an authoring
|
||||
error the operator sees at deploy, not a Bad tag or a dark alarm set afterwards. `Warn` ships anyway (findings in
|
||||
the accepted message); `Off` disables the check. **Upgrade note:** after upgrading to an allow-list build, the first
|
||||
deploy is rejected if any in-use stored script uses an API now refused; see `docs/VirtualTags.md`
|
||||
§"Deploy-time script compile gate".
|
||||
|
||||
Residual exposure, by design: a script can still burn CPU and memory up to its budget (`ScriptRunGuard`; pre-emptive
|
||||
limits need `OutOfProcess`), read any tag through `ctx.GetTag`, and write virtual tags. Extending the allow-list is a
|
||||
security change — add only types with no I/O, process-wide state, background work, blocking wait or reflection
|
||||
|
||||
@@ -87,6 +87,35 @@ public static class EquipmentScriptPaths
|
||||
+ m.Groups[3].Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <see cref="SubstituteEquipmentToken"/> cannot change how <paramref name="source"/> COMPILES: every
|
||||
/// path-literal content it would replace, and every replacement RawPath, is free of <c>\</c>, <c>"</c>, CR and LF.
|
||||
/// Substitution only ever rewrites the content of a <c>ctx.GetTag</c>/<c>ctx.SetVirtualTag</c> string literal;
|
||||
/// with no escape sequence, quote or line break on either side the literal stays one well-formed regular string
|
||||
/// token of type <c>string</c>, and a C# compile (binding, overload resolution, the sandbox analyzer) never depends
|
||||
/// on such a literal's characters. So the resolved source compiles exactly as the template does — which lets the
|
||||
/// deploy-time script compile gate (lmxopcua#971 follow-up) compile a template once instead of once per
|
||||
/// equipment. False ⇒ compile the resolved source itself. Identity cases (no token, empty map) are true.
|
||||
/// </summary>
|
||||
/// <param name="source">The template script source.</param>
|
||||
/// <param name="referenceMap">The owning equipment's reference map: effective name → backing-tag RawPath.</param>
|
||||
/// <returns>True when the substituted source compiles identically to <paramref name="source"/>.</returns>
|
||||
public static bool SubstitutionPreservesCompilation(string? source, IReadOnlyDictionary<string, string> referenceMap)
|
||||
{
|
||||
if (string.IsNullOrEmpty(source) || referenceMap is null || referenceMap.Count == 0) return true;
|
||||
if (!source.Contains(EquipTokenPrefix, StringComparison.Ordinal)) return true;
|
||||
foreach (Match m in PathLiteralRegex.Matches(source))
|
||||
{
|
||||
var content = m.Groups[2].Value;
|
||||
var replaced = SubstituteContent(content, referenceMap);
|
||||
if (ReferenceEquals(replaced, content) || replaced == content) continue;
|
||||
if (!IsPlainLiteralText(content) || !IsPlainLiteralText(replaced)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool IsPlainLiteralText(string text) => text.AsSpan().IndexOfAny("\\\"\r\n") < 0;
|
||||
|
||||
// Substitute the reference-relative token inside a single path-literal's content. The content is one
|
||||
// whole tag path; when it starts with the {{equip}}/ prefix the remainder is the reference name.
|
||||
private static string SubstituteContent(string content, IReadOnlyDictionary<string, string> referenceMap)
|
||||
|
||||
@@ -402,8 +402,9 @@ public static class DraftValidator
|
||||
/// not edges) and run <see cref="DependencyGraph.DetectCycles"/> (Tarjan SCC). Any SCC / self-loop is a
|
||||
/// deploy error naming the cycle members — an undetected calc cycle is a live oscillation loop.</item>
|
||||
/// </list>
|
||||
/// Compile is deliberately NOT hard-gated (VirtualTag parity — the editor's live diagnostics mirror it and
|
||||
/// a runtime compile failure lands as Bad quality + a script-log).</summary>
|
||||
/// Compile is not checked HERE — this validator is Roslyn-free. The deploy gate compiles every in-use script
|
||||
/// (VirtualTag, Calculation, scripted-alarm predicate) separately, through <c>IDeployScriptChecker</c> in
|
||||
/// <c>AdminOperationsActor</c> (<c>Deployment:ScriptCompileGateMode</c>, lmxopcua#971 follow-up).</summary>
|
||||
private static void ValidateCalculationTags(DraftSnapshot draft, List<ValidationError> errors)
|
||||
{
|
||||
var driverTypeByInstance = draft.DriverInstances
|
||||
@@ -673,8 +674,11 @@ public static class DraftValidator
|
||||
}
|
||||
|
||||
/// <summary>Builds the shared <see cref="RawPathResolver"/> from the draft's raw topology so the
|
||||
/// tagname-length rule computes the SAME RawPath the deploy artifact injects into drivers.</summary>
|
||||
private static RawPathResolver BuildRawPathResolver(DraftSnapshot draft)
|
||||
/// tagname-length rule computes the SAME RawPath the deploy artifact injects into drivers. Public so the
|
||||
/// deploy-time script compile gate resolves <c>{{equip}}</c> over the same topology (lmxopcua#971 follow-up).</summary>
|
||||
/// <param name="draft">The draft snapshot.</param>
|
||||
/// <returns>The resolver over the draft's raw folder/driver/device/tag-group topology.</returns>
|
||||
public static RawPathResolver BuildRawPathResolver(DraftSnapshot draft)
|
||||
{
|
||||
var folders = draft.RawFolders.GroupBy(f => f.RawFolderId, StringComparer.Ordinal)
|
||||
.ToDictionary(g => g.Key, g => ((string?)g.First().ParentRawFolderId, g.First().Name), StringComparer.Ordinal);
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
/// <summary>Which script context (and result type) a script compiles against.</summary>
|
||||
/// <remarks>
|
||||
/// Physically defined in the Roslyn-free Core.Scripting.Abstractions assembly (moved from Core.Scripting by the
|
||||
/// lmxopcua#971 follow-up) so the deploy gate's <see cref="IDeployScriptChecker"/> can name it from ControlPlane;
|
||||
/// the namespace is unchanged, so consumers' using-directives are too.
|
||||
/// </remarks>
|
||||
public enum ScriptContextKind
|
||||
{
|
||||
/// <summary>A virtual tag: <c>VirtualTagContext</c> → <c>object?</c>.</summary>
|
||||
VirtualTag = 1,
|
||||
|
||||
/// <summary>A Calculation tag: <c>VirtualTagContext</c> → <c>object?</c>.</summary>
|
||||
Calculation = 2,
|
||||
|
||||
/// <summary>A scripted-alarm predicate: <c>AlarmPredicateContext</c> → <c>bool</c>.</summary>
|
||||
AlarmPredicate = 3,
|
||||
}
|
||||
|
||||
/// <summary>One script to check: the source the runtime will compile, and the seam it will compile for.</summary>
|
||||
/// <param name="Kind">The seam — decides the globals/context type and result type the source compiles against.</param>
|
||||
/// <param name="Source">The source exactly as the runtime receives it (any <c>{{equip}}</c> token already resolved).</param>
|
||||
public sealed record DeployScriptCheckRequest(ScriptContextKind Kind, string Source);
|
||||
|
||||
/// <summary>The outcome for one <see cref="DeployScriptCheckRequest"/>.</summary>
|
||||
/// <param name="Request">The request this answers.</param>
|
||||
/// <param name="Problems">
|
||||
/// Why the runtime would refuse the script — each the same text the runtime reports (<c>compile error: …</c>,
|
||||
/// <c>sandbox violation: …</c>, <c>dependency extraction rejected — …</c>). Empty = the runtime compile accepts it.
|
||||
/// </param>
|
||||
public sealed record DeployScriptCheckResult(DeployScriptCheckRequest Request, IReadOnlyList<string> Problems)
|
||||
{
|
||||
/// <summary>True when the runtime compile accepts the script.</summary>
|
||||
public bool Passed => Problems.Count == 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The deploy-time script compile gate (lmxopcua#971 follow-up). Answers, for each script a deployment carries,
|
||||
/// whether the runtime would compile it — the same Roslyn compile + <c>ForbiddenTypeAnalyzer</c> allow-list the
|
||||
/// VirtualTag, Calculation and scripted-alarm seams run — without emitting or loading anything.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Compiler-free on purpose: ControlPlane (which owns the deploy gate) is Roslyn-free, so it depends on this
|
||||
/// interface and the Host binds the Roslyn implementation (<c>RoslynDeployScriptChecker</c> in Core.Scripting).
|
||||
/// Absent ⇒ the deploy gate skips the check. Implementations must be thread-safe.
|
||||
/// </remarks>
|
||||
public interface IDeployScriptChecker
|
||||
{
|
||||
/// <summary>Checks every request; results are in request order.</summary>
|
||||
/// <param name="requests">The scripts to check.</param>
|
||||
/// <param name="cancellationToken">Cancels the remaining checks.</param>
|
||||
/// <returns>One result per request, same order.</returns>
|
||||
IReadOnlyList<DeployScriptCheckResult> Check(
|
||||
IReadOnlyList<DeployScriptCheckRequest> requests, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -69,18 +69,8 @@ public interface IScriptRunner
|
||||
/// <summary>A runner that owns invocation physical leases until underlying execution actually completes.</summary>
|
||||
public interface IPhysicalScriptRunner : IScriptRunner { }
|
||||
|
||||
/// <summary>Which script context (and result type) a script compiles against.</summary>
|
||||
public enum ScriptContextKind
|
||||
{
|
||||
/// <summary>A virtual tag: <c>VirtualTagContext</c> → <c>object?</c>.</summary>
|
||||
VirtualTag = 1,
|
||||
|
||||
/// <summary>A Calculation tag: <c>VirtualTagContext</c> → <c>object?</c>.</summary>
|
||||
Calculation = 2,
|
||||
|
||||
/// <summary>A scripted-alarm predicate: <c>AlarmPredicateContext</c> → <c>bool</c>.</summary>
|
||||
AlarmPredicate = 3,
|
||||
}
|
||||
// ScriptContextKind lives in Core.Scripting.Abstractions (same namespace) since the lmxopcua#971 follow-up, so the
|
||||
// Roslyn-free deploy gate (IDeployScriptChecker) can name it.
|
||||
|
||||
/// <summary>One evaluation handed to an <see cref="IScriptRunner"/>.</summary>
|
||||
/// <param name="Key">The script instance key (virtual-tag id, calc RawPath, alarm id).</param>
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
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
|
||||
{
|
||||
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);
|
||||
}
|
||||
@@ -82,6 +82,49 @@ public sealed class ScriptEvaluator<TContext, TResult> : IDisposable
|
||||
/// <exception cref="CompilationErrorException">The source does not compile.</exception>
|
||||
/// <exception cref="ScriptSandboxViolationException">The source uses a forbidden API.</exception>
|
||||
public static byte[] CompileToImage(string scriptSource)
|
||||
{
|
||||
var compilation = BuildCheckedCompilation(scriptSource, out var syntaxTree);
|
||||
|
||||
// Step 3a — stack-depth guard (lmxopcua#779). Insert ScriptStackGuard.Check() at the entry of the script
|
||||
// body and of every lambda / anonymous method / local function, so unbounded recursion fails the script with
|
||||
// a catchable exception instead of a StackOverflowException that terminates the server. After the analyzer,
|
||||
// so the analyzer and its diagnostics only ever see the user's code. The rewrite is designed to bind exactly
|
||||
// as the original did; an emit failure here is an internal defect, reported like any other emit failure.
|
||||
var guardedTree = ScriptStackGuardInjector.Inject(compilation, syntaxTree);
|
||||
compilation = compilation.ReplaceSyntaxTree(syntaxTree, guardedTree);
|
||||
|
||||
// Step 4 — emit to an in-memory PE stream and load into a collectible ALC.
|
||||
using var peStream = new MemoryStream();
|
||||
var emitResult = compilation.Emit(peStream);
|
||||
if (!emitResult.Success)
|
||||
{
|
||||
var emitErrors = emitResult.Diagnostics
|
||||
.Where(d => d.Severity == DiagnosticSeverity.Error)
|
||||
.ToArray();
|
||||
throw new CompilationErrorException(emitErrors);
|
||||
}
|
||||
|
||||
return peStream.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every step of <see cref="CompileToImage"/> that can reject a USER script — wrap + parse, the
|
||||
/// wrapper-injection guard, the sandbox compile and <see cref="ForbiddenTypeAnalyzer"/> — with no stack-guard
|
||||
/// rewrite and no emit (those fail only on internal defects). The deploy-time script compile gate
|
||||
/// (lmxopcua#971 follow-up, <c>RoslynDeployScriptChecker</c>) calls this, and it builds its compilation
|
||||
/// through the SAME <see cref="BuildCheckedCompilation"/> the runtime compile does, so the gate accepts a
|
||||
/// source exactly when the runtime compile would.
|
||||
/// </summary>
|
||||
/// <param name="scriptSource">The user script source code to check.</param>
|
||||
/// <exception cref="CompilationErrorException">The source does not compile.</exception>
|
||||
/// <exception cref="ScriptSandboxViolationException">The source uses a forbidden API.</exception>
|
||||
public static void Verify(string scriptSource) => _ = BuildCheckedCompilation(scriptSource, out _);
|
||||
|
||||
/// <summary>
|
||||
/// Steps 1–3 of the compile pipeline, shared by <see cref="CompileToImage"/> (runtime) and
|
||||
/// <see cref="Verify"/> (deploy gate): returns the checked compilation and its wrapper tree, or throws.
|
||||
/// </summary>
|
||||
private static CSharpCompilation BuildCheckedCompilation(string scriptSource, out SyntaxTree syntaxTree)
|
||||
{
|
||||
if (scriptSource is null) throw new ArgumentNullException(nameof(scriptSource));
|
||||
|
||||
@@ -91,7 +134,7 @@ public sealed class ScriptEvaluator<TContext, TResult> : IDisposable
|
||||
// wrapper's `Run` method is what we invoke at runtime; the user's source is
|
||||
// pasted in as its body so explicit `return` semantics apply.
|
||||
var wrapperSource = BuildWrapperSource(scriptSource, sandbox.Imports);
|
||||
var syntaxTree = CSharpSyntaxTree.ParseText(wrapperSource);
|
||||
syntaxTree = CSharpSyntaxTree.ParseText(wrapperSource);
|
||||
|
||||
// Step 1a — defend against wrapper-source injection.
|
||||
// A script body of `return 0; } public static int Evil() { return 0;` would
|
||||
@@ -134,26 +177,7 @@ public sealed class ScriptEvaluator<TContext, TResult> : IDisposable
|
||||
if (rejections.Count > 0)
|
||||
throw new ScriptSandboxViolationException(rejections);
|
||||
|
||||
// Step 3a — stack-depth guard (lmxopcua#779). Insert ScriptStackGuard.Check() at the entry of the script
|
||||
// body and of every lambda / anonymous method / local function, so unbounded recursion fails the script with
|
||||
// a catchable exception instead of a StackOverflowException that terminates the server. After the analyzer,
|
||||
// so the analyzer and its diagnostics only ever see the user's code. The rewrite is designed to bind exactly
|
||||
// as the original did; an emit failure here is an internal defect, reported like any other emit failure.
|
||||
var guardedTree = ScriptStackGuardInjector.Inject(compilation, syntaxTree);
|
||||
compilation = compilation.ReplaceSyntaxTree(syntaxTree, guardedTree);
|
||||
|
||||
// Step 4 — emit to an in-memory PE stream and load into a collectible ALC.
|
||||
using var peStream = new MemoryStream();
|
||||
var emitResult = compilation.Emit(peStream);
|
||||
if (!emitResult.Success)
|
||||
{
|
||||
var emitErrors = emitResult.Diagnostics
|
||||
.Where(d => d.Severity == DiagnosticSeverity.Error)
|
||||
.ToArray();
|
||||
throw new CompilationErrorException(emitErrors);
|
||||
}
|
||||
|
||||
return peStream.ToArray();
|
||||
return compilation;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -28,6 +28,11 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
private readonly IReadOnlyDictionary<string, IDriverProbe> _probesByType;
|
||||
private readonly TagConfigValidationMode _tagConfigValidationMode;
|
||||
|
||||
/// <summary>lmxopcua#971 follow-up: the deploy-time script compile gate; null = not wired, or mode Off.</summary>
|
||||
private readonly IDeployScriptChecker? _scriptChecker;
|
||||
|
||||
private readonly ScriptCompileGateMode _scriptCompileGateMode;
|
||||
|
||||
/// <summary>
|
||||
/// The coordinator's apply deadline. A <c>Dispatching</c> row with no expected-ack rows that is older
|
||||
/// than this is a lost dispatch, closed by the in-flight check (fix round 1 / I7).
|
||||
@@ -59,6 +64,8 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
/// </param>
|
||||
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
||||
/// <param name="alarmVerdictWindow">#950: how long an <c>/alerts</c> ack/shelve waits for the nodes' verdicts; defaults to <see cref="AlarmCommandVerdictCollector.DefaultWindow"/>.</param>
|
||||
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
|
||||
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
|
||||
/// <returns>Props configured to create an AdminOperationsActor.</returns>
|
||||
public static Props Props(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
||||
@@ -67,9 +74,12 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
||||
IActorRef? meshRouter = null,
|
||||
TimeSpan? applyDeadline = null,
|
||||
TimeSpan? alarmVerdictWindow = null) =>
|
||||
TimeSpan? alarmVerdictWindow = null,
|
||||
IDeployScriptChecker? scriptChecker = null,
|
||||
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) =>
|
||||
Akka.Actor.Props.Create(() =>
|
||||
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, alarmVerdictWindow));
|
||||
new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline,
|
||||
alarmVerdictWindow, scriptChecker, scriptCompileGateMode));
|
||||
|
||||
/// <summary>Initializes a new instance of the AdminOperationsActor.</summary>
|
||||
/// <param name="dbFactory">Factory for creating config database contexts.</param>
|
||||
@@ -79,6 +89,8 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
/// <param name="meshRouter">Central comm actor, or <see langword="null"/> for the mediator.</param>
|
||||
/// <param name="applyDeadline">The coordinator's apply deadline; defaults to <see cref="DeployTimings.ApplyDeadline"/> (the coordinator's default source).</param>
|
||||
/// <param name="alarmVerdictWindow">#950: the <c>/alerts</c> verdict collection window.</param>
|
||||
/// <param name="scriptChecker">lmxopcua#971 follow-up: the deploy-time script compile gate, or <see langword="null"/> to skip it.</param>
|
||||
/// <param name="scriptCompileGateMode">How a refused script is treated (Error default | Warn | Off).</param>
|
||||
public AdminOperationsActor(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory,
|
||||
IActorRef coordinator,
|
||||
@@ -86,8 +98,12 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn,
|
||||
IActorRef? meshRouter = null,
|
||||
TimeSpan? applyDeadline = null,
|
||||
TimeSpan? alarmVerdictWindow = null)
|
||||
TimeSpan? alarmVerdictWindow = null,
|
||||
IDeployScriptChecker? scriptChecker = null,
|
||||
ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error)
|
||||
{
|
||||
_scriptChecker = scriptCompileGateMode == ScriptCompileGateMode.Off ? null : scriptChecker;
|
||||
_scriptCompileGateMode = scriptCompileGateMode;
|
||||
_alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow;
|
||||
// The same source the coordinator's default reads (ConfigPublishCoordinator.DefaultApplyDeadline IS
|
||||
// DeployTimings.ApplyDeadline), so the lost-dispatch closure and the coordinator's own deadline agree.
|
||||
@@ -466,6 +482,15 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
/// </summary>
|
||||
private async Task<ComposeOutcome> ComposeDeploymentAsync(StartDeployment msg, string sourceNode, ComposePhaseTimer phases)
|
||||
{
|
||||
// lmxopcua#971 follow-up: warm the script compile gate's cache BEFORE the snapshot transaction + compose app
|
||||
// lock, so the Roslyn work does not run while they are held. The authoritative check runs on the snapshot
|
||||
// below; with the cache warm it is (almost always) all hits.
|
||||
if (_scriptChecker is not null)
|
||||
{
|
||||
await WarmScriptCompileGateAsync(_scriptChecker).ConfigureAwait(false);
|
||||
phases.Mark("script-gate-warm");
|
||||
}
|
||||
|
||||
// lmxopcua#949: phase timings, logged only when the deploy is slow (see ComposePhaseTimer).
|
||||
await using var db = await _dbFactory.CreateDbContextAsync();
|
||||
// ONE transaction holds the snapshot read, the scope-revision advance and the Deployment row, committed
|
||||
@@ -585,6 +610,35 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
_log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w);
|
||||
|
||||
phases.Mark("validate");
|
||||
|
||||
// lmxopcua#971 follow-up — the deploy-time script compile gate: every script the runtime will compile
|
||||
// (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags), {{equip}} resolved exactly as the
|
||||
// compose seams resolve it, through the same compile + allow-list analyzer the runtime runs. On the SAME
|
||||
// snapshot as everything else (R03:3.2); the warm-up above means this is normally all cache hits.
|
||||
var scriptWarnings = new List<string>();
|
||||
if (_scriptChecker is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var f in DeployScriptGate.Run(_scriptChecker, draft))
|
||||
{
|
||||
if (_scriptCompileGateMode == ScriptCompileGateMode.Error)
|
||||
errors.Add(new ValidationError(DeployScriptGate.ErrorCode, f.Text, f.ScriptId));
|
||||
else
|
||||
{
|
||||
scriptWarnings.Add(f.Text);
|
||||
_log.Warning("StartDeployment: script compile warning (Warn mode, non-blocking): {Warning}", f.Text);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// An internal checker failure must not block every deploy; the gate is skipped and says so.
|
||||
_log.Error(ex, "StartDeployment: script compile gate failed internally; skipped for this deploy (correlation {CorrelationId})", msg.CorrelationId);
|
||||
scriptWarnings.Add("script compile gate skipped (internal error; see the central log)");
|
||||
}
|
||||
phases.Mark("script-gate");
|
||||
}
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
phases.LogIfSlow(_log, msg, outcome: "rejected");
|
||||
@@ -677,6 +731,7 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
if (advisory is not null) messageParts.Add(advisory);
|
||||
messageParts.AddRange(tagConfigWarnings.Select(x => x.Text));
|
||||
messageParts.AddRange(writableWarnings);
|
||||
messageParts.AddRange(scriptWarnings);
|
||||
var acceptedMessage = messageParts.Count > 0 ? string.Join("; ", messageParts) : null;
|
||||
|
||||
return new ComposeOutcome(
|
||||
@@ -689,6 +744,34 @@ public sealed class AdminOperationsActor : ReceiveActor
|
||||
new DispatchDeployment(deploymentId, revHash, msg.CorrelationId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#971 follow-up: warms the script compile gate's cache from the three small script tables (no
|
||||
/// Tags read), outside any transaction. Best-effort — a failure here is logged and the authoritative
|
||||
/// in-transaction pass does the work instead.
|
||||
/// </summary>
|
||||
/// <param name="checker">The compile checker.</param>
|
||||
private async Task WarmScriptCompileGateAsync(IDeployScriptChecker checker)
|
||||
{
|
||||
try
|
||||
{
|
||||
await using var db = await _dbFactory.CreateDbContextAsync().ConfigureAwait(false);
|
||||
var scripts = await db.Scripts.AsNoTracking()
|
||||
.Select(s => new { s.ScriptId, s.SourceCode })
|
||||
.ToListAsync().ConfigureAwait(false);
|
||||
if (scripts.Count == 0) return;
|
||||
var vtScriptIds = await db.VirtualTags.AsNoTracking().Where(v => v.Enabled)
|
||||
.Select(v => v.ScriptId).Distinct().ToListAsync().ConfigureAwait(false);
|
||||
var predicateScriptIds = await db.ScriptedAlarms.AsNoTracking().Where(a => a.Enabled)
|
||||
.Select(a => a.PredicateScriptId).Distinct().ToListAsync().ConfigureAwait(false);
|
||||
checker.Check(DeployScriptGate.WarmRequests(
|
||||
scripts.Select(s => (s.ScriptId, s.SourceCode)), vtScriptIds, predicateScriptIds));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.Warning(ex, "StartDeployment: script compile gate warm-up failed; the in-snapshot check runs cold");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test Connect runs on the thread pool and pipes its reply straight to the requester: a probe
|
||||
/// against a black-holed PLC (60 s clamp) must not suspend the singleton's mailbox (R03:3.1). Every
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||
|
||||
/// <summary>
|
||||
/// The deploy-time script compile gate's draft side (lmxopcua#971 follow-up): turns a <see cref="DraftSnapshot"/>
|
||||
/// into the scripts the runtime will compile — each with the seam it compiles for and the source exactly as that
|
||||
/// seam receives it — hands them to an <see cref="IDeployScriptChecker"/>, and folds the verdicts back onto the
|
||||
/// scripts and the entities that use them. Roslyn-free; the compile itself lives behind the checker.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>What is checked mirrors what runs:</para>
|
||||
/// <list type="bullet">
|
||||
/// <item><b>Enabled VirtualTags</b> (a disabled one is materialised but never evaluated) — source with the
|
||||
/// owning equipment's <c>{{equip}}/<RefName></c> substituted, exactly as both compose seams
|
||||
/// (<c>AddressSpaceComposer</c> / <c>DeploymentArtifact</c>) do, through the shared
|
||||
/// <see cref="EquipmentReferenceMap"/> over <see cref="DraftValidator.BuildRawPathResolver"/>.</item>
|
||||
/// <item><b>Enabled scripted alarms</b> (a disabled plan is skipped by the alarm host) — predicate source,
|
||||
/// substituted the same way.</item>
|
||||
/// <item><b>Calculation tags of enabled Calculation drivers</b> — the source verbatim (the artifact injects it
|
||||
/// into the tag's TagConfig with no substitution).</item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// When <see cref="EquipmentScriptPaths.SubstitutionPreservesCompilation"/> proves the substitution cannot
|
||||
/// change how the source compiles (the common case), the TEMPLATE is what is sent — so a VirtualTag template
|
||||
/// shared by 500 equipments is one compile, not 500. Otherwise the resolved source itself is compiled.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class DeployScriptGate
|
||||
{
|
||||
/// <summary>The finding code a refused script is reported under (Error mode).</summary>
|
||||
public const string ErrorCode = "ScriptCompileFailed";
|
||||
|
||||
/// <summary>Most using entities named in one finding before it says "+N more".</summary>
|
||||
internal const int MaxUsersNamed = 5;
|
||||
|
||||
/// <summary>One script use: which script, as what seam, by which entity, and what will be compiled.</summary>
|
||||
/// <param name="ScriptId">The Script row.</param>
|
||||
/// <param name="Kind">The seam it compiles for.</param>
|
||||
/// <param name="UsedBy">The using entity, for the operator (e.g. <c>VirtualTag 'vt-1' (equipment 'EQ-1')</c>).</param>
|
||||
/// <param name="EntityId">The using entity's id.</param>
|
||||
/// <param name="CompileSource">The source sent to the checker (resolved, or the equivalent template).</param>
|
||||
public sealed record ScriptUse(string ScriptId, ScriptContextKind Kind, string UsedBy, string EntityId, string CompileSource);
|
||||
|
||||
/// <summary>A refused script, grouped over every entity that uses it the same way.</summary>
|
||||
/// <param name="ScriptId">The Script row.</param>
|
||||
/// <param name="Kind">The seam it was compiled for.</param>
|
||||
/// <param name="UsedBy">Every using entity, ordinal.</param>
|
||||
/// <param name="Problems">Why the runtime would refuse it (the runtime's own failure text).</param>
|
||||
public sealed record Finding(string ScriptId, ScriptContextKind Kind, IReadOnlyList<string> UsedBy, IReadOnlyList<string> Problems)
|
||||
{
|
||||
/// <summary>The operator-facing sentence: names the script, the seam, the users and the problems.</summary>
|
||||
public string Text
|
||||
{
|
||||
get
|
||||
{
|
||||
var named = string.Join(", ", UsedBy.Take(MaxUsersNamed));
|
||||
var more = UsedBy.Count > MaxUsersNamed ? $" (+{UsedBy.Count - MaxUsersNamed} more)" : string.Empty;
|
||||
return $"script '{ScriptId}' does not compile as a {KindLabel(Kind)} (used by {named}{more}): "
|
||||
+ string.Join("; ", Problems);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Human label for a seam.</summary>
|
||||
/// <param name="kind">The seam.</param>
|
||||
/// <returns>The label.</returns>
|
||||
public static string KindLabel(ScriptContextKind kind) => kind switch
|
||||
{
|
||||
ScriptContextKind.VirtualTag => "VirtualTag script",
|
||||
ScriptContextKind.Calculation => "Calculation script",
|
||||
ScriptContextKind.AlarmPredicate => "scripted-alarm predicate",
|
||||
_ => kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Every script use the runtime will compile, in a deterministic order.</summary>
|
||||
/// <param name="draft">The draft snapshot being deployed.</param>
|
||||
/// <returns>The uses.</returns>
|
||||
public static IReadOnlyList<ScriptUse> CollectUses(DraftSnapshot draft)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(draft);
|
||||
var uses = new List<ScriptUse>();
|
||||
var sourceById = draft.Scripts
|
||||
.GroupBy(s => s.ScriptId, StringComparer.Ordinal)
|
||||
.ToDictionary(g => g.Key, g => g.First().SourceCode ?? string.Empty, StringComparer.Ordinal);
|
||||
if (sourceById.Count == 0) return uses;
|
||||
|
||||
// {{equip}}/<RefName> → RawPath — the same authority + resolver as the compose seams and DraftValidator.
|
||||
var resolver = DraftValidator.BuildRawPathResolver(draft);
|
||||
var tagsById = draft.Tags
|
||||
.GroupBy(t => t.TagId, StringComparer.Ordinal)
|
||||
.ToDictionary(
|
||||
g => g.Key,
|
||||
g => new EquipmentReferenceMap.TagRow(g.First().Name, g.First().DeviceId, g.First().TagGroupId),
|
||||
StringComparer.Ordinal);
|
||||
var referenceMapByEquip = EquipmentReferenceMap.Build(
|
||||
draft.UnsTagReferences.Select(r => new EquipmentReferenceMap.ReferenceRow(
|
||||
r.UnsTagReferenceId, r.EquipmentId, r.TagId, r.DisplayNameOverride)),
|
||||
tagsById, resolver);
|
||||
var noRefs = (IReadOnlyDictionary<string, string>)new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
string Resolve(string template, string equipmentId)
|
||||
{
|
||||
var map = referenceMapByEquip.GetValueOrDefault(equipmentId, noRefs);
|
||||
return EquipmentScriptPaths.SubstitutionPreservesCompilation(template, map)
|
||||
? template
|
||||
: EquipmentScriptPaths.SubstituteEquipmentToken(template, map);
|
||||
}
|
||||
|
||||
foreach (var v in draft.VirtualTags.Where(v => v.Enabled).OrderBy(v => v.VirtualTagId, StringComparer.Ordinal))
|
||||
{
|
||||
if (!sourceById.TryGetValue(v.ScriptId, out var src)) continue; // dangling id: DraftValidator's finding
|
||||
uses.Add(new ScriptUse(v.ScriptId, ScriptContextKind.VirtualTag,
|
||||
$"VirtualTag '{v.VirtualTagId}' (equipment '{v.EquipmentId}')", v.VirtualTagId, Resolve(src, v.EquipmentId)));
|
||||
}
|
||||
|
||||
foreach (var a in draft.ScriptedAlarms.Where(a => a.Enabled).OrderBy(a => a.ScriptedAlarmId, StringComparer.Ordinal))
|
||||
{
|
||||
if (!sourceById.TryGetValue(a.PredicateScriptId, out var src)) continue;
|
||||
uses.Add(new ScriptUse(a.PredicateScriptId, ScriptContextKind.AlarmPredicate,
|
||||
$"ScriptedAlarm '{a.ScriptedAlarmId}' (equipment '{a.EquipmentId}')", a.ScriptedAlarmId,
|
||||
Resolve(src, a.EquipmentId)));
|
||||
}
|
||||
|
||||
var enabledCalcDrivers = draft.DriverInstances
|
||||
.Where(d => d.Enabled && string.Equals(d.DriverType, DriverTypeNames.Calculation, StringComparison.Ordinal))
|
||||
.Select(d => d.DriverInstanceId)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
if (enabledCalcDrivers.Count > 0)
|
||||
{
|
||||
var calcDevices = draft.Devices
|
||||
.Where(d => enabledCalcDrivers.Contains(d.DriverInstanceId))
|
||||
.Select(d => d.DeviceId)
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var t in draft.Tags.Where(t => calcDevices.Contains(t.DeviceId)).OrderBy(t => t.TagId, StringComparer.Ordinal))
|
||||
{
|
||||
var scriptId = DraftValidator.ParseScriptId(t.TagConfig);
|
||||
if (scriptId is null || !sourceById.TryGetValue(scriptId, out var src)) continue;
|
||||
var rawPath = resolver.TryBuildTagPath(t.DeviceId, t.TagGroupId, t.Name);
|
||||
uses.Add(new ScriptUse(scriptId, ScriptContextKind.Calculation,
|
||||
rawPath is null ? $"Calculation tag '{t.TagId}'" : $"Calculation tag '{t.TagId}' ({rawPath})",
|
||||
t.TagId, src));
|
||||
}
|
||||
}
|
||||
|
||||
return uses;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The cache-warming request set, from the three small tables only — no Tags read. Sent BEFORE the deploy's
|
||||
/// snapshot transaction so the authoritative in-transaction pass is (almost always) all cache hits. Each
|
||||
/// script is warmed as the seams that can use it: a predicate of an enabled scripted alarm as
|
||||
/// <see cref="ScriptContextKind.AlarmPredicate"/>; any other script as a value script (VirtualTag and
|
||||
/// Calculation share one compile). Templates only — that is what the gate sends whenever substitution
|
||||
/// preserves compilation.
|
||||
/// </summary>
|
||||
/// <param name="scripts">Script id + source.</param>
|
||||
/// <param name="enabledVirtualTagScriptIds">Script ids of enabled VirtualTags.</param>
|
||||
/// <param name="enabledPredicateScriptIds">Predicate script ids of enabled scripted alarms.</param>
|
||||
/// <returns>The warm-up requests.</returns>
|
||||
public static IReadOnlyList<DeployScriptCheckRequest> WarmRequests(
|
||||
IEnumerable<(string ScriptId, string Source)> scripts,
|
||||
IEnumerable<string> enabledVirtualTagScriptIds,
|
||||
IEnumerable<string> enabledPredicateScriptIds)
|
||||
{
|
||||
var vt = enabledVirtualTagScriptIds.ToHashSet(StringComparer.Ordinal);
|
||||
var predicates = enabledPredicateScriptIds.ToHashSet(StringComparer.Ordinal);
|
||||
var requests = new List<DeployScriptCheckRequest>();
|
||||
foreach (var (id, source) in scripts)
|
||||
{
|
||||
var isPredicate = predicates.Contains(id);
|
||||
if (isPredicate) requests.Add(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, source ?? string.Empty));
|
||||
if (!isPredicate || vt.Contains(id))
|
||||
requests.Add(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source ?? string.Empty));
|
||||
}
|
||||
return requests;
|
||||
}
|
||||
|
||||
/// <summary>Checks every use in <paramref name="draft"/> and returns the refused scripts, grouped.</summary>
|
||||
/// <param name="checker">The compile checker.</param>
|
||||
/// <param name="draft">The draft snapshot being deployed.</param>
|
||||
/// <param name="cancellationToken">Cancellation.</param>
|
||||
/// <returns>The findings, ordered by script id then seam; empty when every used script compiles.</returns>
|
||||
public static IReadOnlyList<Finding> Run(IDeployScriptChecker checker, DraftSnapshot draft, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(checker);
|
||||
var uses = CollectUses(draft);
|
||||
if (uses.Count == 0) return [];
|
||||
|
||||
// One request per distinct (seam, source); the checker caches across deploys as well.
|
||||
var requestIndex = new Dictionary<(ScriptContextKind, string), int>();
|
||||
var requests = new List<DeployScriptCheckRequest>();
|
||||
foreach (var u in uses)
|
||||
{
|
||||
if (requestIndex.ContainsKey((u.Kind, u.CompileSource))) continue;
|
||||
requestIndex[(u.Kind, u.CompileSource)] = requests.Count;
|
||||
requests.Add(new DeployScriptCheckRequest(u.Kind, u.CompileSource));
|
||||
}
|
||||
var results = checker.Check(requests, cancellationToken);
|
||||
if (results.Count != requests.Count)
|
||||
throw new InvalidOperationException(
|
||||
$"IDeployScriptChecker returned {results.Count} result(s) for {requests.Count} request(s).");
|
||||
|
||||
return uses
|
||||
.Select(u => (Use: u, Problems: results[requestIndex[(u.Kind, u.CompileSource)]].Problems))
|
||||
.Where(x => x.Problems.Count > 0)
|
||||
.GroupBy(x => (x.Use.ScriptId, x.Use.Kind, Problems: string.Join("\n", x.Problems)))
|
||||
.OrderBy(g => g.Key.ScriptId, StringComparer.Ordinal)
|
||||
.ThenBy(g => g.Key.Kind)
|
||||
.Select(g => new Finding(
|
||||
g.Key.ScriptId,
|
||||
g.Key.Kind,
|
||||
g.Select(x => x.Use.UsedBy).Distinct(StringComparer.Ordinal).OrderBy(s => s, StringComparer.Ordinal).ToList(),
|
||||
g.First().Problems))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||
|
||||
/// <summary>
|
||||
/// How the deploy gate treats a script the runtime would refuse to compile (lmxopcua#971 follow-up). Sourced from
|
||||
/// <c>Deployment:ScriptCompileGateMode</c> in appsettings; defaults to <see cref="Error"/>. Takes effect only when
|
||||
/// an <c>IDeployScriptChecker</c> is registered (the Host binds one on admin nodes).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Why <see cref="Error"/> is the default</b> (unlike <see cref="TagConfigValidationMode"/>, which defaults to
|
||||
/// Warn): a script that fails this gate never runs — a VirtualTag or Calculation tag publishes Bad
|
||||
/// (<c>compile error</c> / <c>sandbox violation</c>) for as long as it is deployed, and one failing
|
||||
/// scripted-alarm predicate fails the whole scripted-alarm load, so EVERY scripted alarm on the node goes dark.
|
||||
/// Blocking the deploy therefore blocks no working behaviour — only a deployment that carries a definitely
|
||||
/// broken script — and it is the only mode in which "the editor rejects ⇔ publish rejects" holds. A tolerated
|
||||
/// TagConfig typo, by contrast, used to run (the runtime silently defaulted it), which is why that gate stayed
|
||||
/// Warn.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Upgrade note:</b> lmxopcua#971 narrowed the script sandbox to an allow-list, so a stored, in-use script
|
||||
/// that compiled before the upgrade can now be refused. The first deploy after upgrading is then REJECTED,
|
||||
/// naming each script and the entities that use it — fix the script, disable the using VirtualTag / scripted
|
||||
/// alarm, or set <c>Deployment:ScriptCompileGateMode=Warn</c> to ship anyway (the script stays broken at
|
||||
/// runtime either way: nodes recompile the running artifact on restart, so the gate cannot make a refused
|
||||
/// script work — it only stops new deploys from carrying one silently).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public enum ScriptCompileGateMode
|
||||
{
|
||||
/// <summary>Blocking: a refused script folds into the reject list (<c>ScriptCompileFailed</c>). The default.</summary>
|
||||
Error,
|
||||
|
||||
/// <summary>Non-blocking: findings are logged and appended to the accepted <c>StartDeploymentResult.Message</c>.</summary>
|
||||
Warn,
|
||||
|
||||
/// <summary>The gate does not run (no compile cost at deploy time).</summary>
|
||||
Off,
|
||||
}
|
||||
@@ -18,6 +18,7 @@ using ZB.MOM.WW.OtOpcUa.ControlPlane.Fleet;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Redundancy;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Retention;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane;
|
||||
|
||||
@@ -34,6 +35,19 @@ public static class ServiceCollectionExtensions
|
||||
public const string ClusterNodeAddressReconcilerSingletonName = "cluster-node-address-reconciler";
|
||||
public const string DeploymentRetentionSingletonName = "deployment-retention";
|
||||
|
||||
/// <summary>
|
||||
/// Parses <c>Deployment:ScriptCompileGateMode</c> (lmxopcua#971 follow-up). Absent, blank or unrecognised ⇒
|
||||
/// <see cref="ScriptCompileGateMode.Error"/>: a typo never silently weakens the gate (and never stops the
|
||||
/// admin singleton from starting, which a throw inside its props factory would).
|
||||
/// </summary>
|
||||
/// <param name="value">The configured value.</param>
|
||||
/// <returns>The mode.</returns>
|
||||
public static ScriptCompileGateMode ParseScriptCompileGateMode(string? value) =>
|
||||
Enum.TryParse<ScriptCompileGateMode>(value?.Trim(), ignoreCase: true, out var mode)
|
||||
&& Enum.IsDefined(mode) && !int.TryParse(value, out _)
|
||||
? mode
|
||||
: ScriptCompileGateMode.Error;
|
||||
|
||||
/// <summary>
|
||||
/// Registers the admin-role cluster singletons on the AkkaConfigurationBuilder — three with
|
||||
/// registry proxies, plus the address reconciler, which is proxy-less because nothing addresses it.
|
||||
@@ -132,11 +146,18 @@ public static class ServiceCollectionExtensions
|
||||
var mode = Enum.TryParse<TagConfigValidationMode>(
|
||||
resolver.GetService<IConfiguration>()?["Deployment:TagConfigValidationMode"],
|
||||
ignoreCase: true, out var m) ? m : TagConfigValidationMode.Warn;
|
||||
// lmxopcua#971 follow-up: the deploy-time script compile gate. The checker is optional (the Host binds
|
||||
// the Roslyn one on admin nodes; this project stays Roslyn-free) — through IServiceProvider for
|
||||
// GetService's null-for-absent contract. Mode: Deployment:ScriptCompileGateMode = Error default | Warn | Off.
|
||||
var scriptChecker = resolver.GetService<IServiceProvider>()?.GetService<IDeployScriptChecker>();
|
||||
var scriptMode = ParseScriptCompileGateMode(
|
||||
resolver.GetService<IConfiguration>()?["Deployment:ScriptCompileGateMode"]);
|
||||
var meshRouter = registry.Get<CentralCommunicationActorKey>();
|
||||
// The SAME deadline source as the coordinator above: AdminOps closes a lost dispatch only once it
|
||||
// is past the coordinator's deadline, so the two must never drift.
|
||||
return AdminOperationsActor.Props(dbFactory, coordinator, probes, mode, meshRouter,
|
||||
applyDeadline: DeployTimings.ApplyDeadline);
|
||||
applyDeadline: DeployTimings.ApplyDeadline,
|
||||
scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode);
|
||||
},
|
||||
singletonOptions);
|
||||
|
||||
|
||||
@@ -181,6 +181,10 @@ if (hasAdmin)
|
||||
// lmxopcua#868: the deploy coordinator singleton reports its ConfigDb recovery-load state here; the
|
||||
// config-publish health check (AddOtOpcUaHealth) reads it — Degraded while deployments are queued.
|
||||
builder.Services.AddSingleton<ZB.MOM.WW.OtOpcUa.ControlPlane.Coordinators.ConfigPublishCoordinatorReadiness>();
|
||||
// lmxopcua#971 follow-up: the deploy-time script compile gate. ControlPlane is Roslyn-free and resolves this
|
||||
// optionally (absent ⇒ the gate is skipped); Deployment:ScriptCompileGateMode picks Error (default) | Warn | Off.
|
||||
builder.Services.AddSingleton<ZB.MOM.WW.OtOpcUa.Core.Scripting.IDeployScriptChecker,
|
||||
ZB.MOM.WW.OtOpcUa.Core.Scripting.RoslynDeployScriptChecker>(_ => new ZB.MOM.WW.OtOpcUa.Core.Scripting.RoslynDeployScriptChecker());
|
||||
}
|
||||
else
|
||||
Log.Information("Driver-only node — no ConfigDb registered; configuration via ConfigSource:Mode=FetchAndCache");
|
||||
|
||||
@@ -255,4 +255,41 @@ public class EquipmentScriptPathsTests
|
||||
EquipmentScriptPaths.TryParseRelayBody(src, out var r).ShouldBeFalse();
|
||||
r.ShouldBeNull();
|
||||
}
|
||||
|
||||
// ---- SubstitutionPreservesCompilation (lmxopcua#971 follow-up: the deploy compile gate's template dedupe) ----
|
||||
|
||||
[Theory]
|
||||
[InlineData("return ctx.GetTag(\"{{equip}}/Speed\").Value;")] // plain substitution
|
||||
[InlineData("return ctx.GetTag(\"Plant/Literal\").Value;")] // no token
|
||||
[InlineData("return ctx.GetTag(\"{{equip}}/Missing\").Value;")] // unresolved: unchanged
|
||||
[InlineData("ctx.SetVirtualTag(\"{{equip}}/Out\", 1); return ctx.GetTag(\"{{equip}}/A\").Value;")]
|
||||
[InlineData("")]
|
||||
public void SubstitutionPreservesCompilation_true_when_only_escape_free_literal_text_changes(string src)
|
||||
{
|
||||
EquipmentScriptPaths.SubstitutionPreservesCompilation(src, RefMap).ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubstitutionPreservesCompilation_false_when_a_replacement_carries_an_escape_character()
|
||||
{
|
||||
// A backslash in a RawPath would become an escape sequence inside the literal — compile the resolved source.
|
||||
var map = new Dictionary<string, string>(StringComparer.Ordinal) { ["Speed"] = @"Cell1\Dev\Speed" };
|
||||
EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Speed\").Value;", map)
|
||||
.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubstitutionPreservesCompilation_false_when_the_replaced_text_carries_an_escape()
|
||||
{
|
||||
var map = new Dictionary<string, string>(StringComparer.Ordinal) { [@"Sp\eed"] = "Cell1/Dev/Speed" };
|
||||
EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Sp\\eed\").Value;", map)
|
||||
.ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SubstitutionPreservesCompilation_empty_map_is_identity()
|
||||
{
|
||||
EquipmentScriptPaths.SubstitutionPreservesCompilation(
|
||||
"return ctx.GetTag(\"{{equip}}/Speed\").Value;", new Dictionary<string, string>()).ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#971 follow-up — the deploy-time script compile gate's Roslyn side. The gate must answer exactly as the
|
||||
/// runtime seam would: same compile, same allow-list, per seam (a VirtualTag/Calculation compiles as
|
||||
/// <c>VirtualTagContext → object?</c>, a scripted-alarm predicate as <c>AlarmPredicateContext → bool</c> after the
|
||||
/// dependency extractor), and cached so a redeploy does not re-enter Roslyn.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class RoslynDeployScriptCheckerTests
|
||||
{
|
||||
private const string Legit = "var v = ctx.GetTag(\"A\").Value; return v is null ? 0.0 : Convert.ToDouble(v) * 2;";
|
||||
private const string Forbidden = "return System.IO.File.ReadAllText(\"/etc/passwd\");";
|
||||
private const string Broken = "return undefinedThing + 1;";
|
||||
|
||||
private static DeployScriptCheckResult CheckOne(IDeployScriptChecker checker, ScriptContextKind kind, string source) =>
|
||||
checker.Check([new DeployScriptCheckRequest(kind, source)], TestContext.Current.CancellationToken).Single();
|
||||
|
||||
[Fact]
|
||||
public void A_legitimate_script_passes_positive_control()
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue();
|
||||
CheckOne(checker, ScriptContextKind.Calculation, Legit).Passed.ShouldBeTrue();
|
||||
CheckOne(checker, ScriptContextKind.AlarmPredicate, "return Convert.ToDouble(ctx.GetTag(\"A\").Value ?? 0.0) > 5;")
|
||||
.Passed.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_forbidden_api_is_a_sandbox_violation()
|
||||
{
|
||||
var result = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.VirtualTag, Forbidden);
|
||||
result.Passed.ShouldBeFalse();
|
||||
result.Problems.Single().ShouldStartWith("sandbox violation: ");
|
||||
result.Problems.Single().ShouldContain("File");
|
||||
result.Problems.Single().ShouldNotContain("\n");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_compile_error_is_reported_as_the_runtime_reports_it()
|
||||
{
|
||||
var result = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.VirtualTag, Broken);
|
||||
result.Problems.Single().ShouldStartWith("compile error: ");
|
||||
result.Problems.Single().ShouldContain("undefinedThing");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_seam_decides_the_compile_a_non_bool_result_fails_only_as_an_alarm_predicate()
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
const string returnsDouble = "return 1.5;";
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, returnsDouble).Passed.ShouldBeTrue();
|
||||
var asPredicate = CheckOne(checker, ScriptContextKind.AlarmPredicate, returnsDouble);
|
||||
asPredicate.Passed.ShouldBeFalse();
|
||||
asPredicate.Problems.Single().ShouldStartWith("compile error: ");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_alarm_predicate_runs_the_dependency_extractor_first_a_virtual_tag_does_not()
|
||||
{
|
||||
// A non-literal tag path: the scripted-alarm load rejects it before compiling; the VirtualTag seam never
|
||||
// runs the extractor, so the same source compiles there.
|
||||
const string dynamicPath = "var p = \"A\"; return ctx.GetTag(p).Value is null;";
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, dynamicPath).Passed.ShouldBeTrue();
|
||||
CheckOne(checker, ScriptContextKind.AlarmPredicate, dynamicPath)
|
||||
.Problems.Single().ShouldStartWith("dependency extraction rejected — ");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_passthrough_mirror_never_reaches_roslyn_for_value_seams_but_does_for_a_predicate()
|
||||
{
|
||||
const string mirror = "return ctx.GetTag(\"Plant/Dev/Speed\").Value;";
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, mirror).Passed.ShouldBeTrue();
|
||||
CheckOne(checker, ScriptContextKind.Calculation, mirror).Passed.ShouldBeTrue();
|
||||
checker.CompilesPerformed.ShouldBe(0);
|
||||
// The alarm engine always compiles — and object is not bool.
|
||||
CheckOne(checker, ScriptContextKind.AlarmPredicate, mirror).Passed.ShouldBeFalse();
|
||||
checker.CompilesPerformed.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Verdicts_are_cached_by_source_and_compile_identity()
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse();
|
||||
checker.CompilesPerformed.ShouldBe(1);
|
||||
|
||||
// Cache hit: same source, same seam — and Calculation shares the VirtualTag compile.
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse();
|
||||
CheckOne(checker, ScriptContextKind.Calculation, Forbidden).Passed.ShouldBeFalse();
|
||||
checker.CompilesPerformed.ShouldBe(1);
|
||||
|
||||
// A different compile identity is a miss.
|
||||
CheckOne(checker, ScriptContextKind.AlarmPredicate, Forbidden).Passed.ShouldBeFalse();
|
||||
checker.CompilesPerformed.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_batch_compiles_each_distinct_source_once_and_answers_in_request_order()
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker(maxParallelism: 4);
|
||||
var requests = new[]
|
||||
{
|
||||
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit),
|
||||
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Forbidden),
|
||||
new DeployScriptCheckRequest(ScriptContextKind.Calculation, Legit),
|
||||
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Broken),
|
||||
new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Forbidden),
|
||||
};
|
||||
var results = checker.Check(requests, TestContext.Current.CancellationToken);
|
||||
results.Select(r => r.Request).ShouldBe(requests);
|
||||
results.Select(r => r.Passed).ShouldBe([true, false, true, false, false]);
|
||||
checker.CompilesPerformed.ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_full_cache_is_cleared_and_still_answers_correctly()
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker(capacity: 1);
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue();
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse();
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue();
|
||||
checker.CompilesPerformed.ShouldBe(3);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parity with the runtime compile: <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> shares the
|
||||
/// compilation factory with <see cref="ScriptEvaluator{TContext, TResult}.CompileToImage"/>, so for every
|
||||
/// sample the gate passes exactly when the runtime compile succeeds.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(Legit)]
|
||||
[InlineData(Forbidden)]
|
||||
[InlineData(Broken)]
|
||||
[InlineData("return 1.5;")]
|
||||
[InlineData("return true;")]
|
||||
[InlineData("return 0; } public static int Evil() { return 0;")]
|
||||
[InlineData("var t = typeof(string).Assembly; return t.FullName;")]
|
||||
[InlineData("return Environment.GetEnvironmentVariable(\"PATH\");")]
|
||||
public void The_gate_accepts_exactly_what_the_runtime_compile_accepts(string source)
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
|
||||
static bool RuntimeCompiles<TContext, TResult>(string s) where TContext : ScriptContext
|
||||
{
|
||||
try { _ = ScriptEvaluator<TContext, TResult>.CompileToImage(s); return true; }
|
||||
catch (CompilationErrorException) { return false; }
|
||||
catch (ScriptSandboxViolationException) { return false; }
|
||||
}
|
||||
|
||||
CheckOne(checker, ScriptContextKind.VirtualTag, source).Passed
|
||||
.ShouldBe(RuntimeCompiles<VirtualTagContext, object?>(source));
|
||||
var predicateRuntime = DependencyExtractor.Extract(source).IsValid && RuntimeCompiles<AlarmPredicateContext, bool>(source);
|
||||
CheckOne(checker, ScriptContextKind.AlarmPredicate, source).Passed.ShouldBe(predicateRuntime);
|
||||
}
|
||||
}
|
||||
+321
@@ -0,0 +1,321 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Akka.Actor;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
|
||||
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#971 follow-up — the deploy-time script compile gate, exercised THROUGH the actor with the real Roslyn
|
||||
/// checker (and a recording fake where the test is about what is sent). A script the runtime would refuse blocks
|
||||
/// the deploy in Error mode (the default) and rides the accepted message in Warn mode; a legitimate draft deploys
|
||||
/// clean (the positive control every reject test leans on); each seam compiles as itself; {{equip}} is resolved
|
||||
/// before compiling; an absent checker or mode Off skips the gate.
|
||||
/// </summary>
|
||||
public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneActorTestBase
|
||||
{
|
||||
private const string Legit = "var v = ctx.GetTag(\"{{equip}}/speed\").Value; return v is null ? 0.0 : Convert.ToDouble(v) * 2;";
|
||||
// Reads a tag so the draft is otherwise valid (a VirtualTag with no input never triggers — a DraftValidator error).
|
||||
private const string Forbidden =
|
||||
"var v = ctx.GetTag(\"{{equip}}/speed\").Value; return v is null ? null : System.IO.File.ReadAllText(\"/etc/passwd\");";
|
||||
private const string LegitPredicate = "return Convert.ToDouble(ctx.GetTag(\"{{equip}}/speed\").Value ?? 0.0) > 5;";
|
||||
private const string LegitCalc = "return Convert.ToDouble(ctx.GetTag(\"plant/drv/dev/speed\").Value ?? 0.0) + 1;";
|
||||
private const string CleanModbus = "{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\"}";
|
||||
|
||||
private sealed record Seed(
|
||||
string VtSource = Legit, string PredicateSource = LegitPredicate, string CalcSource = LegitCalc,
|
||||
bool VtEnabled = true, bool AlarmEnabled = true, int Equipments = 1, bool SharedVtScript = true, string DeviceName = "dev");
|
||||
|
||||
/// <summary>A complete, DraftValidator-clean draft: area/line/equipment(s), a Modbus tag referenced into each
|
||||
/// equipment as <c>speed</c>, a VirtualTag + scripted alarm per equipment, and one Calculation tag.</summary>
|
||||
private static IDbContextFactory<OtOpcUaConfigDbContext> SeedDraft(Seed seed)
|
||||
{
|
||||
var dbFactory = NewInMemoryDbFactory();
|
||||
using var db = dbFactory.CreateDbContext();
|
||||
db.RawFolders.Add(new RawFolder { RawFolderId = "rf-plant", ClusterId = "", Name = "plant" });
|
||||
db.DriverInstances.Add(new DriverInstance
|
||||
{
|
||||
DriverInstanceId = "d-1", ClusterId = "", RawFolderId = "rf-plant", Name = "drv", DriverType = "Modbus", DriverConfig = "{}",
|
||||
});
|
||||
db.Devices.Add(new Device { DeviceId = "dev-1", DriverInstanceId = "d-1", Name = seed.DeviceName, DeviceConfig = "{}" });
|
||||
db.Tags.Add(new Tag
|
||||
{
|
||||
TagId = "tag-speed", DeviceId = "dev-1", Name = "speed", DataType = "Int16",
|
||||
AccessLevel = TagAccessLevel.Read, TagConfig = CleanModbus,
|
||||
});
|
||||
|
||||
db.DriverInstances.Add(new DriverInstance
|
||||
{
|
||||
DriverInstanceId = "d-calc", ClusterId = "", RawFolderId = "rf-plant", Name = "calc",
|
||||
DriverType = DriverTypeNames.Calculation, DriverConfig = "{}",
|
||||
});
|
||||
db.Devices.Add(new Device { DeviceId = "dev-calc", DriverInstanceId = "d-calc", Name = "cdev", DeviceConfig = "{}" });
|
||||
db.Tags.Add(new Tag
|
||||
{
|
||||
TagId = "tag-calc", DeviceId = "dev-calc", Name = "sum", DataType = "Double",
|
||||
AccessLevel = TagAccessLevel.Read, TagConfig = "{\"scriptId\":\"s-calc\"}",
|
||||
});
|
||||
|
||||
db.UnsAreas.Add(new UnsArea { UnsAreaId = "area-1", ClusterId = "", Name = "area" });
|
||||
db.UnsLines.Add(new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" });
|
||||
|
||||
db.Scripts.Add(new Script { ScriptId = "s-pred", Name = "pred", SourceCode = seed.PredicateSource, SourceHash = "h-pred" });
|
||||
db.Scripts.Add(new Script { ScriptId = "s-calc", Name = "calc", SourceCode = seed.CalcSource, SourceHash = "h-calc" });
|
||||
for (var i = 1; i <= seed.Equipments; i++)
|
||||
{
|
||||
var uuid = Guid.NewGuid();
|
||||
var equipmentId = DraftValidator.DeriveEquipmentId(uuid);
|
||||
db.Equipment.Add(new Equipment
|
||||
{
|
||||
EquipmentUuid = uuid, EquipmentId = equipmentId, Name = $"eq{i}", UnsLineId = "line-1", MachineCode = $"m{i}",
|
||||
});
|
||||
db.UnsTagReferences.Add(new UnsTagReference { UnsTagReferenceId = $"ref-{i}", EquipmentId = equipmentId, TagId = "tag-speed" });
|
||||
var vtScriptId = seed.SharedVtScript ? "s-vt" : $"s-vt-{i}";
|
||||
if (!seed.SharedVtScript || i == 1)
|
||||
db.Scripts.Add(new Script { ScriptId = vtScriptId, Name = vtScriptId, SourceCode = seed.VtSource, SourceHash = "h-" + vtScriptId });
|
||||
db.VirtualTags.Add(new VirtualTag
|
||||
{
|
||||
VirtualTagId = $"vt-{i}", EquipmentId = equipmentId, Name = "doubled", DataType = "Double",
|
||||
ScriptId = vtScriptId, Enabled = seed.VtEnabled,
|
||||
});
|
||||
db.ScriptedAlarms.Add(new ScriptedAlarm
|
||||
{
|
||||
ScriptedAlarmId = $"al-{i}", EquipmentId = equipmentId, Name = "high", AlarmType = "LimitAlarm",
|
||||
MessageTemplate = "speed high", PredicateScriptId = "s-pred", Enabled = seed.AlarmEnabled,
|
||||
});
|
||||
}
|
||||
db.SaveChanges();
|
||||
return dbFactory;
|
||||
}
|
||||
|
||||
private StartDeploymentResult Deploy(
|
||||
IDbContextFactory<OtOpcUaConfigDbContext> dbFactory, IDeployScriptChecker? checker,
|
||||
ScriptCompileGateMode mode = ScriptCompileGateMode.Error, bool expectDispatch = true)
|
||||
{
|
||||
var coordinator = CreateTestProbe();
|
||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(
|
||||
dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(),
|
||||
scriptChecker: checker, scriptCompileGateMode: mode));
|
||||
actor.Tell(new StartDeployment("joe", CorrelationId.NewId()));
|
||||
if (expectDispatch) coordinator.ExpectMsg<DispatchDeployment>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
else coordinator.ExpectNoMsg(TimeSpan.FromMilliseconds(300), TestContext.Current.CancellationToken);
|
||||
return ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Records every request and answers from a rule; optionally throws.</summary>
|
||||
private sealed class RecordingChecker(Func<DeployScriptCheckRequest, IReadOnlyList<string>>? rule = null, bool @throw = false)
|
||||
: IDeployScriptChecker
|
||||
{
|
||||
public ConcurrentQueue<DeployScriptCheckRequest> Requests { get; } = new();
|
||||
|
||||
public ConcurrentQueue<IReadOnlyList<DeployScriptCheckRequest>> Calls { get; } = new();
|
||||
|
||||
public IReadOnlyList<DeployScriptCheckResult> Check(IReadOnlyList<DeployScriptCheckRequest> requests, CancellationToken cancellationToken = default)
|
||||
{
|
||||
Calls.Enqueue(requests.ToList());
|
||||
foreach (var r in requests) Requests.Enqueue(r);
|
||||
if (@throw) throw new InvalidOperationException("checker exploded");
|
||||
return requests.Select(r => new DeployScriptCheckResult(r, rule?.Invoke(r) ?? [])).ToList();
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_legitimate_draft_deploys_clean_positive_control()
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
var reply = Deploy(SeedDraft(new Seed()), checker);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message);
|
||||
(reply.Message ?? string.Empty).ShouldNotContain("does not compile");
|
||||
checker.CompilesPerformed.ShouldBeGreaterThan(0); // the gate really ran
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_forbidden_api_blocks_the_deploy_in_error_mode_naming_the_script_and_its_users()
|
||||
{
|
||||
var dbFactory = SeedDraft(new Seed(VtSource: Forbidden, Equipments: 2));
|
||||
var reply = Deploy(dbFactory, new RoslynDeployScriptChecker(), expectDispatch: false);
|
||||
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
||||
reply.Message.ShouldNotBeNull();
|
||||
reply.Message.ShouldContain(DeployScriptGate.ErrorCode);
|
||||
reply.Message.ShouldContain("script 's-vt'");
|
||||
reply.Message.ShouldContain("VirtualTag 'vt-1'");
|
||||
reply.Message.ShouldContain("VirtualTag 'vt-2'"); // one finding, both users
|
||||
reply.Message.ShouldContain("sandbox violation");
|
||||
using var verify = dbFactory.CreateDbContext();
|
||||
verify.Deployments.Count().ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Error_is_the_default_mode()
|
||||
{
|
||||
var dbFactory = SeedDraft(new Seed(VtSource: Forbidden));
|
||||
var coordinator = CreateTestProbe();
|
||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(
|
||||
dbFactory, coordinator.Ref, Enumerable.Empty<IDriverProbe>(), scriptChecker: new RoslynDeployScriptChecker()));
|
||||
actor.Tell(new StartDeployment("joe", CorrelationId.NewId()));
|
||||
ExpectMsg<StartDeploymentResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken)
|
||||
.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
||||
ServiceCollectionExtensions.ParseScriptCompileGateMode(null).ShouldBe(ScriptCompileGateMode.Error);
|
||||
ServiceCollectionExtensions.ParseScriptCompileGateMode("Warning").ShouldBe(ScriptCompileGateMode.Error);
|
||||
ServiceCollectionExtensions.ParseScriptCompileGateMode("7").ShouldBe(ScriptCompileGateMode.Error);
|
||||
ServiceCollectionExtensions.ParseScriptCompileGateMode("warn").ShouldBe(ScriptCompileGateMode.Warn);
|
||||
ServiceCollectionExtensions.ParseScriptCompileGateMode(" Off ").ShouldBe(ScriptCompileGateMode.Off);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Warn_mode_accepts_and_surfaces_the_finding_in_the_message()
|
||||
{
|
||||
var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden)), new RoslynDeployScriptChecker(), ScriptCompileGateMode.Warn);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted);
|
||||
reply.Message.ShouldNotBeNull();
|
||||
reply.Message.ShouldContain("script 's-vt'");
|
||||
reply.Message.ShouldContain("sandbox violation");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Each_seam_compiles_as_itself_a_value_script_used_as_a_predicate_is_refused()
|
||||
{
|
||||
// `return 1.5;` is a fine VirtualTag / Calculation body and a non-bool predicate.
|
||||
const string returnsDouble = "return 1.5;";
|
||||
var reply = Deploy(SeedDraft(new Seed(VtSource: returnsDouble, PredicateSource: returnsDouble, CalcSource: returnsDouble)),
|
||||
new RoslynDeployScriptChecker(), expectDispatch: false);
|
||||
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
||||
reply.Message.ShouldNotBeNull();
|
||||
reply.Message.ShouldContain("script 's-pred' does not compile as a scripted-alarm predicate");
|
||||
reply.Message.ShouldContain("ScriptedAlarm 'al-1'");
|
||||
reply.Message.ShouldNotContain("script 's-vt'");
|
||||
reply.Message.ShouldNotContain("script 's-calc'");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_forbidden_calculation_script_names_the_calculation_tag()
|
||||
{
|
||||
var reply = Deploy(SeedDraft(new Seed(CalcSource: Forbidden)), new RoslynDeployScriptChecker(), expectDispatch: false);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
||||
reply.Message.ShouldNotBeNull();
|
||||
reply.Message.ShouldContain("script 's-calc' does not compile as a Calculation script");
|
||||
reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Disabled_users_are_not_checked_they_never_compile_at_runtime()
|
||||
{
|
||||
var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden, PredicateSource: Forbidden, VtEnabled: false, AlarmEnabled: false)),
|
||||
new RoslynDeployScriptChecker());
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_absent_checker_skips_the_gate()
|
||||
{
|
||||
var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden)), checker: null);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mode_off_skips_the_gate_and_never_calls_the_checker()
|
||||
{
|
||||
var checker = new RecordingChecker(_ => ["compile error: nope"]);
|
||||
var reply = Deploy(SeedDraft(new Seed()), checker, ScriptCompileGateMode.Off);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message);
|
||||
checker.Requests.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Equip_tokens_resolve_before_compiling_and_a_template_is_sent_once_for_every_equipment()
|
||||
{
|
||||
// Three equipments share one VT template: substitution only rewrites escape-free literal text, so the gate
|
||||
// sends the template once per seam rather than three resolved copies.
|
||||
var checker = new RecordingChecker();
|
||||
var reply = Deploy(SeedDraft(new Seed(Equipments: 3)), checker);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message);
|
||||
|
||||
// Two passes: the warm-up outside the transaction, then the authoritative in-snapshot pass.
|
||||
checker.Calls.Count.ShouldBe(2);
|
||||
var inSnapshotPass = checker.Calls.Last();
|
||||
// One request per (seam, source): the shared template once — no per-equipment resolved copies.
|
||||
inSnapshotPass.Count.ShouldBe(3);
|
||||
inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit));
|
||||
inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, LegitPredicate));
|
||||
inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.Calculation, LegitCalc));
|
||||
// The warm-up asked for the same template, so the in-snapshot pass is a cache hit on a real checker.
|
||||
checker.Calls.First().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Collected_uses_resolve_equip_exactly_as_the_compose_seams_do()
|
||||
{
|
||||
// The draft-side collection on its own: the substitution the gate reasons about is the compose seams' one.
|
||||
var dbFactory = SeedDraft(new Seed(Equipments: 1));
|
||||
using var db = dbFactory.CreateDbContext();
|
||||
var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, TestContext.Current.CancellationToken);
|
||||
var uses = DeployScriptGate.CollectUses(draft);
|
||||
|
||||
var vt = uses.Single(u => u.Kind == ScriptContextKind.VirtualTag);
|
||||
vt.CompileSource.ShouldBe(Legit); // equivalent template sent…
|
||||
EquipmentScriptPaths.SubstituteEquipmentToken(Legit,
|
||||
new Dictionary<string, string> { ["speed"] = "plant/drv/dev/speed" })
|
||||
.ShouldContain("ctx.GetTag(\"plant/drv/dev/speed\")"); // …for what the seams will run
|
||||
uses.Single(u => u.Kind == ScriptContextKind.AlarmPredicate).UsedBy.ShouldContain("ScriptedAlarm 'al-1'");
|
||||
uses.Single(u => u.Kind == ScriptContextKind.Calculation).UsedBy.ShouldContain("Calculation tag 'tag-calc'");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A RawPath segment may legally contain a backslash, and substitution pastes the RawPath into a C# string
|
||||
/// literal — so <c>{{equip}}/speed</c> over a device named <c>de\qv</c> becomes an invalid escape the runtime
|
||||
/// refuses to compile. The template compiles fine; only compiling the RESOLVED source (what the gate does
|
||||
/// whenever substitution is not provably compile-neutral) catches it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void An_equip_substitution_that_breaks_the_literal_is_caught_by_compiling_the_resolved_source()
|
||||
{
|
||||
var reply = Deploy(SeedDraft(new Seed(DeviceName: @"de\qv")), new RoslynDeployScriptChecker(), expectDispatch: false);
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected);
|
||||
reply.Message.ShouldNotBeNull();
|
||||
reply.Message.ShouldContain("script 's-vt' does not compile as a VirtualTag script");
|
||||
reply.Message.ShouldContain("compile error");
|
||||
reply.Message.ShouldContain("script 's-pred'"); // the predicate resolves through the same reference
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_cache_makes_a_redeploy_compile_nothing()
|
||||
{
|
||||
var checker = new RoslynDeployScriptChecker();
|
||||
var dbFactory = SeedDraft(new Seed(Equipments: 2));
|
||||
Deploy(dbFactory, checker).Outcome.ShouldBe(StartDeploymentOutcome.Accepted);
|
||||
var afterFirst = checker.CompilesPerformed;
|
||||
afterFirst.ShouldBeGreaterThan(0);
|
||||
|
||||
// Close the first deployment so the next one is not refused as in-flight.
|
||||
using (var db = dbFactory.CreateDbContext())
|
||||
{
|
||||
foreach (var d in db.Deployments) d.Status = DeploymentStatus.Sealed;
|
||||
db.SaveChanges();
|
||||
}
|
||||
Deploy(dbFactory, checker).Outcome.ShouldBe(StartDeploymentOutcome.Accepted);
|
||||
checker.CompilesPerformed.ShouldBe(afterFirst);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_internal_checker_failure_never_blocks_the_deploy()
|
||||
{
|
||||
var reply = Deploy(SeedDraft(new Seed()), new RecordingChecker(@throw: true));
|
||||
reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted);
|
||||
reply.Message.ShouldNotBeNull();
|
||||
reply.Message.ShouldContain("script compile gate skipped");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user