feat(deploy): #971 follow-up deploy-time script compile gate

The deploy gate never compiled scripts, so a stored script the #971 allow-list
now refuses only failed after the deploy (VirtualTag/Calculation Bad "sandbox
violation", scripted-alarm load failing for every alarm on the node).

- Core.Scripting.Abstractions: IDeployScriptChecker (Roslyn-free) + request/result
  records; ScriptContextKind moved here (same namespace).
- Core.Scripting: ScriptEvaluator.Verify shares a private BuildCheckedCompilation
  factory with CompileToImage (wrap, injection guard, sandbox compile,
  ForbiddenTypeAnalyzer; no stack-guard rewrite, no emit). RoslynDeployScriptChecker
  checks per seam (VT/Calc as VirtualTagContext->object?, passthrough/blank skipped;
  predicates DependencyExtractor first then AlarmPredicateContext->bool), caches by
  (compile identity, SHA-256), parallel, bounded.
- ControlPlane: DeployScriptGate collects enabled VTs / enabled alarm predicates /
  Calculation tags, resolves {{equip}} through EquipmentReferenceMap exactly as the
  compose seams do (template compiled once when SubstitutionPreservesCompilation,
  else the resolved source), groups findings per script naming its users.
  AdminOperationsActor warms the cache before the snapshot transaction and runs the
  authoritative pass on the same snapshot; Deployment:ScriptCompileGateMode =
  Error (default) | Warn | Off; an absent checker or an internal failure never blocks.
- Host binds RoslynDeployScriptChecker on admin nodes.
- Docs: VirtualTags.md (gate + upgrade note), ScriptEditor.md, security.md, CLAUDE.md.

Found while testing: {{equip}} substitution pastes RawPaths into C# literals
unescaped, so a segment containing \ or " breaks (or silently alters) the
script; the gate now reports it at deploy.
This commit is contained in:
Joseph Doherty
2026-12-03 11:29:32 -05:00
parent 67682af520
commit 6e912bb070
18 changed files with 1226 additions and 42 deletions
@@ -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}}/&lt;RefName&gt;</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");