fix(uns): #978 one UNS name authority and a script-reference gate — an illegal VirtualTag name or override is refused in the editor and at publish, and an in-use script cannot be deleted

- V3NodeIds.ValidateSegment is the single rule Uns()/UnsChild() enforce; the VirtualTag modal
  ([UnsLeafName]), UnsTreeService (VirtualTag create/update, SetReferenceOverrideAsync) and the
  deploy gate (VirtualTagNameInvalid, UnsEffectiveNameInvalid) all call it (C-1, C-4).
- Effective name is stated once (EquipmentReferenceMap.EffectiveName): an empty override falls
  back to the tag name in the gate and the Monaco catalog, as at both compose seams (C-4).
- UnsSegment patterns anchored \A..\z, so a trailing newline is rejected (C-7).
- VirtualTagScriptNotFound / ScriptedAlarmScriptNotFound deploy-gate rules; ScriptEdit refuses to
  delete a script used by a VirtualTag, ScriptedAlarm or Calculation tag and names them (C-2).
- R-5 backstop: VirtualTagHostActor skips (Error log) a plan whose NodeId cannot be built instead
  of crashing on every apply; AddressSpaceApplier counts it as a failed node instead of aborting
  the VirtualTag materialise pass.
This commit is contained in:
Joseph Doherty
2026-12-03 10:28:27 -05:00
parent be5641fc06
commit d2818e2ef2
23 changed files with 814 additions and 21 deletions
+12
View File
@@ -131,6 +131,18 @@ deploy gate (`DraftValidator`, `UnsEffectiveNameCollision`) — the deploy gate
what catches **rename-induced** collisions a raw rename produced after the
reference was authored, naming both colliding sources and the equipment.
**One name authority (lmxopcua#978).** An effective name is a UNS NodeId leaf, so it must
pass `V3NodeIds.ValidateSegment` — the exact rule `V3NodeIds.Uns`/`UnsChild` throw on
(non-empty, no `/`, no leading/trailing whitespace). The VirtualTag modal (`[UnsLeafName]`),
`UnsTreeService` (VirtualTag create/update, `SetReferenceOverrideAsync`) and the deploy gate
(`VirtualTagNameInvalid`, `UnsEffectiveNameInvalid` for a non-empty `DisplayNameOverride`) all call
it, so the editor accepts exactly what publish accepts. Before this a VirtualTag named `Flow/Rate`
sealed and then threw in the address-space apply on every node, and an override `Temp/Inlet`
deployed green with the variable silently missing. An **empty** override means "use the raw tag
name" everywhere (`EquipmentReferenceMap.EffectiveName`; the gate used to skip it). Area / Line /
Equipment names keep their stricter `UnsSegment` rule, now anchored `\A…\z` so a trailing newline
(e.g. from a quoted CSV field) is rejected.
Removing a raw tag in `/raw` is blocked while a `UnsTagReference` points at it
(the error names the referencing equipment); renaming a raw tag or any ancestor
warns when a beneath-it tag is historized (no `historianTagname` override),
+1
View File
@@ -299,6 +299,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT
- **`{{equip}}/<Name>` does not resolve a VirtualTag** — that token resolves `UnsTagReference` rows only. `EquipReferenceUnresolved` now says so when the name is a VirtualTag on that equipment and names the key form to use.
- **AdminUI.** The script editor's completion/hover catalog (`ScriptTagCatalog`) lists each VirtualTag under its key instead of its bare leaf name.
- Pinned by `VirtualTagToVirtualTagFlowTests` (Host.Tests: real mux + host + Roslyn evaluator; value, change and disabled-upstream propagation), `VirtualTagOutputRoutingTests` (Runtime.Tests: mux pinning/replay/release, host routing, re-assert exclusion, runtime cycle backstop) and `DraftValidatorVirtualTagCycleTests`.
- **Names and scripts are gated (lmxopcua#978).** A VirtualTag `Name` is its UNS NodeId leaf (`{EquipmentId}/{Name}`), so the modal, `UnsTreeService` and the deploy gate (`VirtualTagNameInvalid`) all apply `V3NodeIds.ValidateSegment` (no `/`, no leading/trailing whitespace). Every VirtualTag `ScriptId` and ScriptedAlarm `PredicateScriptId` must name an existing script (`VirtualTagScriptNotFound` / `ScriptedAlarmScriptNotFound`, disabled rows included), and the `/scripts/{id}` delete refuses a script still used by a VirtualTag, ScriptedAlarm or Calculation tag, naming them (`ScriptUsage`; there is no FK, so a concurrent bind is caught by the gate). As a backstop for an artifact that bypassed the gate, `VirtualTagHostActor` skips a plan whose NodeId cannot be built (logged at Error) instead of crashing the host — which used to stop every VirtualTag on the node with nothing re-applying — and `AddressSpaceApplier.MaterialiseEquipmentVirtualTags` counts it as a failed node (degraded apply) instead of aborting the pass. Pinned by `DraftValidatorUnsLeafNameAndScriptTests`, `UnsLeafNameAuthorityTests`, `VirtualTagHostActorTests.An_illegal_name_is_skipped_and_the_good_tags_keep_working` and `ScriptEditLifecycleTests.A_script_in_use_is_not_deleted_and_the_user_is_named`.
- **Timer-driven evaluation (lmxopcua#783).** `VirtualTag.TimerIntervalMs` re-evaluates the tag on a fixed cadence (minimum 50 ms, clamped) via an Akka scheduler owned by `VirtualTagActor` — started in `PreStart`, cancelled in `PostStop`, so a stop or a redeploy respawn never leaves a ticker. `ChangeTriggered=false` makes the timer the only trigger (dependencies are still tracked). A tick that lands while a script run is in flight is dropped rather than stashed, so a slow script never builds a backlog of runs. Before this the field was stored, validated and edited but never consumed, so a timer-only tag sat at `BadWaitingForInitialData` forever. The deploy gate `VirtualTagNoEffectiveTrigger` (mirror of `CalculationNoEffectiveTrigger`) rejects a tag with neither a timer nor a change-trigger with a literal `ctx.GetTag` read. Pinned by `VirtualTagActorTimerTests` and `DraftValidatorVirtualTagTriggerTests`.
- **Calculation tags and scripted alarms still evaluate one script at a time per driver / per engine (deliberately, for now).** Neither blocks a thread — both await the run — but a slow script still delays its siblings. Running independent scripts in parallel was considered for #779 and not done, because it is not semantics-neutral: for Calculation, the single pump is what bounds a driver to one pool thread of script work (per-tag lanes would let N slow tags hold N pool threads, the pool Akka's dispatchers also run on, so it needs a bounded-parallelism knob), it would reorder publishes across tags, and the timer path would need per-tag exclusion with the pump; for scripted alarms, the engine gate is also the consistency boundary of the Part 9 state machine, persist-before-update and ack/shelve/load, a predicate's transition time is sampled just before its own run, and a store failure mid-batch today leaves later predicates un-run (in parallel they would already have run, moving their run-guard strike streaks and writing script logs for results that are then discarded). The out-of-process runner's batch-submit `IScriptRunner` (#750) is where that concurrency belongs, with the runner owning the bound.
- **`IHistoryWriter`** — the equipment-namespace path threads `Historize` end-to-end and `VirtualTagHostActor` invokes the injected writer on historized results (H5); the writer is resolved through `DriverHostActor` DI with a `NullHistoryWriter` default. No *durable* writer ships on this seam — durable continuous historization now flows through the separate `ContinuousHistorizationRecorder` → HistorianGateway `WriteLiveValues` path (see the `IHistoryWriter` section above and [Historian.md](Historian.md)).
@@ -67,6 +67,18 @@ public static class V3NodeIds
// ----- Uns realm -----
/// <summary>
/// The ONE rule for a UNS NodeId segment — exactly what <see cref="Uns(string[])"/> and
/// <see cref="UnsChild"/> enforce (non-empty, no <see cref="RawPaths.Separator"/>, no leading/trailing
/// whitespace; delegated to <see cref="RawPaths.ValidateSegment"/>). Every authoring surface and deploy-gate
/// rule for a name that becomes a UNS leaf (a VirtualTag <c>Name</c>, a reference's effective name /
/// <c>DisplayNameOverride</c>) calls this, so the editor accepts exactly what the identity authority builds
/// and no name can pass authoring and the gate only to throw at apply time (lmxopcua#978, review C-1/C-4).
/// </summary>
/// <param name="segment">The candidate segment.</param>
/// <returns>A human-readable error when invalid, or <see langword="null"/> when the segment is valid.</returns>
public static string? ValidateSegment(string? segment) => RawPaths.ValidateSegment(segment);
/// <summary>
/// The UNS-namespace <c>s=</c> identifier for a folder or variable, slash-joined from
/// ordered segments (Area, then Line, then Equipment, then an optional EffectiveName).
@@ -94,7 +106,7 @@ public static class V3NodeIds
public static string UnsChild(string parentUnsPath, string childSegment)
{
ArgumentException.ThrowIfNullOrEmpty(parentUnsPath);
var error = RawPaths.ValidateSegment(childSegment);
var error = ValidateSegment(childSegment);
if (error is not null)
throw new ArgumentException($"Invalid UNS NodeId segment ('{childSegment}'): {error}", nameof(childSegment));
@@ -110,7 +122,7 @@ public static class V3NodeIds
for (var i = 0; i < list.Count; i++)
{
var error = RawPaths.ValidateSegment(list[i]);
var error = ValidateSegment(list[i]);
if (error is not null)
throw new ArgumentException($"Invalid UNS NodeId segment at index {i} ('{list[i]}'): {error}", nameof(segments));
}
@@ -30,6 +30,18 @@ public static class EquipmentReferenceMap
/// <param name="TagGroupId">The tag's owning tag-group id, or <see langword="null"/> when directly under the device.</param>
public readonly record struct TagRow(string Name, string DeviceId, string? TagGroupId);
/// <summary>
/// The effective-name rule, stated once: the <paramref name="displayNameOverride"/> when it is non-empty,
/// else the backing raw tag's <paramref name="tagName"/>. An EMPTY override counts as "no override" — the
/// rule both compose seams apply; the deploy gate used <c>??</c> and so skipped an empty-string override
/// the composer materialised under the tag name (lmxopcua#978, review C-4).
/// </summary>
/// <param name="displayNameOverride">The reference's optional override.</param>
/// <param name="tagName">The backing raw tag's Name, or <see langword="null"/> when the tag is unknown.</param>
/// <returns>The effective name, or <see langword="null"/> when neither is available.</returns>
public static string? EffectiveName(string? displayNameOverride, string? tagName) =>
string.IsNullOrEmpty(displayNameOverride) ? tagName : displayNameOverride;
/// <summary>
/// Build the reference map. For each reference (ordered by <c>UnsTagReferenceId</c>), resolve the
/// backing tag's RawPath via <paramref name="resolver"/> and key it under the effective name within
@@ -55,7 +67,7 @@ public static class EquipmentReferenceMap
{
if (string.IsNullOrEmpty(r.EquipmentId) || string.IsNullOrEmpty(r.TagId)) continue;
if (!tagsById.TryGetValue(r.TagId, out var tag)) continue;
var effectiveName = string.IsNullOrEmpty(r.DisplayNameOverride) ? tag.Name : r.DisplayNameOverride!;
var effectiveName = EffectiveName(r.DisplayNameOverride, tag.Name);
if (string.IsNullOrEmpty(effectiveName)) continue;
var rawPath = resolver.TryBuildTagPath(tag.DeviceId, tag.TagGroupId, tag.Name);
if (rawPath is null) continue; // broken chain — dropped (deploy gate rejects invalid names)
@@ -38,8 +38,10 @@ public static class DraftValidator
ValidateRawNameCharset(draft, errors);
ValidateHistorizedTagnameLength(draft, errors);
ValidateHistorianReadOnly(draft, errors);
ValidateUnsLeafNames(draft, errors);
ValidateUnsEffectiveLeafUniqueness(draft, errors);
ValidateEquipReferenceResolution(draft, errors);
ValidateScriptReferences(draft, errors);
ValidateCalculationTags(draft, errors);
ValidateVirtualTagTriggers(draft, errors);
ValidateVirtualTagDependencyCycles(draft, errors);
@@ -505,7 +507,8 @@ public static class DraftValidator
if (!v.Enabled) continue;
if (v.TimerIntervalMs is > 0) continue;
var source = scriptSourceById.TryGetValue(v.ScriptId, out var s) ? s : null;
// An unresolved script is reported elsewhere; with no source there are no reads to count.
// An unresolved script is VirtualTagScriptNotFound (ValidateScriptReferences); with no source there
// are no reads to count.
if (v.ChangeTriggered && source is null) continue;
if (v.ChangeTriggered && EquipmentScriptPaths.ExtractDependencyRefs(source).Count > 0) continue;
errors.Add(new("VirtualTagNoEffectiveTrigger",
@@ -644,8 +647,11 @@ public static class DraftValidator
}
/// <summary>Extract the <c>scriptId</c> string from a calc tag's schemaless <c>TagConfig</c> JSON. Never
/// throws — malformed/blank/non-object JSON or an absent/non-string <c>scriptId</c> yields null.</summary>
private static string? ParseScriptId(string? tagConfig)
/// throws — malformed/blank/non-object JSON or an absent/non-string <c>scriptId</c> yields null. Public so the
/// AdminUI script-delete usage check reads the same key the gate does (lmxopcua#978).</summary>
/// <param name="tagConfig">The tag's TagConfig JSON.</param>
/// <returns>The non-blank <c>scriptId</c>, or <see langword="null"/>.</returns>
public static string? ParseScriptId(string? tagConfig)
{
if (string.IsNullOrWhiteSpace(tagConfig)) return null;
try
@@ -740,6 +746,86 @@ public static class DraftValidator
}
}
/// <summary>The <c>VirtualTagNameInvalid</c> error code (lmxopcua#978).</summary>
public const string VirtualTagNameInvalidCode = "VirtualTagNameInvalid";
/// <summary>The <c>UnsEffectiveNameInvalid</c> error code (lmxopcua#978).</summary>
public const string UnsEffectiveNameInvalidCode = "UnsEffectiveNameInvalid";
/// <summary>The <c>VirtualTagScriptNotFound</c> error code (lmxopcua#978).</summary>
public const string VirtualTagScriptNotFoundCode = "VirtualTagScriptNotFound";
/// <summary>The <c>ScriptedAlarmScriptNotFound</c> error code (lmxopcua#978).</summary>
public const string ScriptedAlarmScriptNotFoundCode = "ScriptedAlarmScriptNotFound";
/// <summary>
/// lmxopcua#978 (review C-1 ≡ R-5, C-4): every name that becomes a UNS leaf NodeId segment must pass
/// <see cref="V3NodeIds.ValidateSegment"/> — the exact rule <see cref="V3NodeIds.Uns(string[])"/> throws on.
/// <list type="bullet">
/// <item>A VirtualTag's <c>Name</c> (its NodeId is <c>{EquipmentId}/{Name}</c>). Unchecked, a
/// <c>Flow/Rate</c> or <c>"Speed "</c> sealed, then threw in the address-space apply and in
/// <c>VirtualTagHostActor</c> on every node, on every later deploy.</item>
/// <item>A reference's non-empty <c>DisplayNameOverride</c> (its effective name). Unchecked, the composer
/// silently dropped the UNS variable. An empty override falls back to the raw tag name, which
/// <c>RawNameInvalid</c> already covers.</item>
/// </list>
/// The authoring surfaces (VirtualTag modal + service, the override editor) call the same method.
/// </summary>
private static void ValidateUnsLeafNames(DraftSnapshot draft, List<ValidationError> errors)
{
foreach (var v in draft.VirtualTags)
{
var error = V3NodeIds.ValidateSegment(v.Name);
if (error is not null)
errors.Add(new(VirtualTagNameInvalidCode,
$"VirtualTag '{v.VirtualTagId}' name '{v.Name}' is not a legal UNS NodeId segment: {error}",
v.VirtualTagId));
}
foreach (var r in draft.UnsTagReferences)
{
if (string.IsNullOrEmpty(r.DisplayNameOverride)) continue;
var error = V3NodeIds.ValidateSegment(r.DisplayNameOverride);
if (error is not null)
errors.Add(new(UnsEffectiveNameInvalidCode,
$"reference '{r.UnsTagReferenceId}' display-name override '{r.DisplayNameOverride}' is not a legal " +
$"UNS NodeId segment: {error}",
r.UnsTagReferenceId));
}
}
/// <summary>
/// lmxopcua#978 (review C-2): every VirtualTag's <c>ScriptId</c> and every ScriptedAlarm's
/// <c>PredicateScriptId</c> must name a script in the draft. The two columns carry no FK, a script delete
/// used to have no usage check, and each downstream layer assumed another enforced it: the composer
/// silently skipped a scripted alarm with a missing predicate (the condition vanished on a green deploy)
/// and deployed a VirtualTag with an empty expression (Bad forever). Disabled rows are included — a
/// dangling reference is a broken row whether or not it is evaluated today, and re-enabling it later must
/// not be the first time anyone hears of it.
/// </summary>
private static void ValidateScriptReferences(DraftSnapshot draft, List<ValidationError> errors)
{
var scriptIds = draft.Scripts.Select(s => s.ScriptId).ToHashSet(StringComparer.Ordinal);
foreach (var v in draft.VirtualTags)
{
if (scriptIds.Contains(v.ScriptId)) continue;
errors.Add(new(VirtualTagScriptNotFoundCode,
$"VirtualTag '{v.VirtualTagId}' references script '{v.ScriptId}', which does not exist in the draft; " +
"pick an existing script or restore the deleted one",
v.VirtualTagId));
}
foreach (var a in draft.ScriptedAlarms)
{
if (scriptIds.Contains(a.PredicateScriptId)) continue;
errors.Add(new(ScriptedAlarmScriptNotFoundCode,
$"ScriptedAlarm '{a.ScriptedAlarmId}' references predicate script '{a.PredicateScriptId}', which does " +
"not exist in the draft; pick an existing script or restore the deleted one",
a.ScriptedAlarmId));
}
}
/// <summary>v3: within an equipment, the EFFECTIVE leaf name must be unique across its UnsTagReferences
/// (DisplayNameOverride else the backing raw tag's Name), its VirtualTags (Name), and its ScriptedAlarms
/// (Name) — the three share the equipment's UNS NodeId space (<c>{EquipmentId}/{EffectiveName}</c>).
@@ -762,7 +848,8 @@ public static class DraftValidator
foreach (var r in draft.UnsTagReferences)
{
var effective = r.DisplayNameOverride ?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
var effective = EquipmentReferenceMap.EffectiveName(
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
Add(r.EquipmentId, effective, $"reference '{r.UnsTagReferenceId}'");
}
foreach (var v in draft.VirtualTags)
@@ -797,7 +884,8 @@ public static class DraftValidator
var refNamesByEquip = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
foreach (var r in draft.UnsTagReferences)
{
var effective = r.DisplayNameOverride ?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
var effective = EquipmentReferenceMap.EffectiveName(
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
if (string.IsNullOrEmpty(effective)) continue;
if (!refNamesByEquip.TryGetValue(r.EquipmentId, out var set))
refNamesByEquip[r.EquipmentId] = set = new HashSet<string>(StringComparer.Ordinal);
@@ -38,15 +38,18 @@ public static class UnsSegment
/// ⚠️ This does <b>not</b> admit <see cref="DefaultSegment"/> — an attribute cannot express the
/// alternation and stay readable. <see cref="AttributePattern"/> is the one to put on a form;
/// <see cref="IsValid"/> is the one to call in code.
/// <para>⚠️ Anchored with <c>\A</c>/<c>\z</c>, never <c>^</c>/<c>$</c>: in .NET <c>$</c> also matches before a
/// final <c>\n</c>, so <c>"press-1\n"</c> passed — through equipment CSV import, then the deploy gate —
/// and the applier dropped the equipment folder after a green deploy (lmxopcua#978, review C-7).</para>
/// </remarks>
public const string Pattern = "^[a-z0-9-]{1,32}$";
public const string Pattern = @"\A[a-z0-9-]{1,32}\z";
/// <summary>
/// <see cref="Pattern"/> widened to admit <see cref="DefaultSegment"/> — the form of the rule to
/// put in a <c>[RegularExpression]</c> attribute, so the UI accepts exactly what the deploy gate
/// accepts and no less.
/// </summary>
public const string AttributePattern = "^([a-z0-9-]{1,32}|_default)$";
public const string AttributePattern = @"\A(?:[a-z0-9-]{1,32}|_default)\z";
/// <summary>The message shown for a rejected segment, in the UI and from the service guards.</summary>
public const string Message =
@@ -233,13 +233,24 @@ else
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == intent.Id);
if (!Current(generation)) return;
if (entity is null) { Nav.NavigateTo("/scripts"); return; }
// lmxopcua#978 (review C-2): no FK protects a script in use, so refuse here and name the users —
// a deleted predicate used to drop its scripted alarm silently on the next green deploy.
var inUse = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.DescribeBlockingUsageAsync(db, intent.Id);
if (!Current(generation)) return;
if (inUse is not null)
{
// Close the confirmation so the page-level alert naming the users is what the operator sees.
_confirmDeleteVisible = false; _deleteIntent = null; ++_confirmationEpoch;
_error = $"Not deleted. {inUse}";
return;
}
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = intent.RowVersion;
db.Scripts.Remove(entity);
await db.SaveChangesAsync();
if (Current(generation)) Nav.NavigateTo("/scripts");
}
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were viewing it."; }
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}. Likely because virtual tags or scripted alarms still reference this script — remove them first."; }
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}."; }
finally { if (Current(generation)) _busy = false; }
}
public void Dispose()
@@ -480,7 +480,8 @@
private sealed class FormModel
{
[Required, RegularExpression("^[A-Za-z0-9_-]+$")] public string VirtualTagId { get; set; } = "";
[Required] public string Name { get; set; } = "";
// lmxopcua#978: the Name is the UNS NodeId leaf ({EquipmentId}/{Name}) — same rule as the deploy gate.
[Required, UnsLeafName] public string Name { get; set; } = "";
public string DataType { get; set; } = "Double";
[Required] public string ScriptId { get; set; } = "";
public bool ChangeTriggered { get; set; } = true;
@@ -144,7 +144,8 @@ public sealed class ScriptTagCatalog(
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var r in refs)
{
var eff = r.DisplayNameOverride ?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
var eff = EquipmentReferenceMap.EffectiveName(
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
if (!string.IsNullOrEmpty(eff)) names.Add(eff!);
}
@@ -0,0 +1,72 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
/// <summary>
/// The script-delete usage check (lmxopcua#978, review C-2). <c>VirtualTag.ScriptId</c>,
/// <c>ScriptedAlarm.PredicateScriptId</c> and a Calculation tag's <c>TagConfig.scriptId</c> carry no FK, so
/// a delete used to succeed against a script in use; the next deploy then silently dropped the scripted alarm
/// (and deployed the VirtualTag with an empty expression). The deploy gate now refuses such a draft
/// (<c>VirtualTagScriptNotFound</c> / <c>ScriptedAlarmScriptNotFound</c> / <c>CalculationScriptNotFound</c>);
/// this stops the delete that would create it, and says which rows hold the script.
/// </summary>
/// <remarks>
/// A check-then-delete is not serialised against a concurrent "bind a VirtualTag to this script" — the deploy
/// gate is the backstop for that window. A real FK (<c>Restrict</c>) would close it but needs a migration.
/// </remarks>
public static class ScriptUsage
{
/// <summary>How many using rows are named in the refusal before it summarises the rest.</summary>
private const int NamedLimit = 5;
/// <summary>
/// Describes every row that references <paramref name="scriptId"/>, or returns <see langword="null"/> when
/// nothing does and the script may be deleted.
/// </summary>
/// <param name="db">The context the delete will run on.</param>
/// <param name="scriptId">The script about to be deleted.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A refusal naming the users, or <see langword="null"/> when the script is unused.</returns>
public static async Task<string?> DescribeBlockingUsageAsync(
OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentException.ThrowIfNullOrEmpty(scriptId);
var users = new List<string>();
var vtags = await db.VirtualTags.AsNoTracking()
.Where(v => v.ScriptId == scriptId)
.OrderBy(v => v.VirtualTagId)
.Select(v => new { v.VirtualTagId, v.Name, v.EquipmentId })
.ToListAsync(ct);
users.AddRange(vtags.Select(v => $"virtual tag '{v.Name}' ({v.VirtualTagId}) on equipment {v.EquipmentId}"));
var alarms = await db.ScriptedAlarms.AsNoTracking()
.Where(a => a.PredicateScriptId == scriptId)
.OrderBy(a => a.ScriptedAlarmId)
.Select(a => new { a.ScriptedAlarmId, a.Name, a.EquipmentId })
.ToListAsync(ct);
users.AddRange(alarms.Select(a => $"scripted alarm '{a.Name}' ({a.ScriptedAlarmId}) on equipment {a.EquipmentId}"));
// Calculation tags hold the id inside schemaless JSON: narrow in SQL by substring, then confirm with the
// same parser the deploy gate uses, so a script id that merely appears in another key never blocks.
var calcCandidates = await db.Tags.AsNoTracking()
.Where(t => t.TagConfig.Contains(scriptId))
.OrderBy(t => t.TagId)
.Select(t => new { t.TagId, t.Name, t.TagConfig })
.ToListAsync(ct);
users.AddRange(calcCandidates
.Where(t => string.Equals(DraftValidator.ParseScriptId(t.TagConfig), scriptId, StringComparison.Ordinal))
.Select(t => $"calculation tag '{t.Name}' ({t.TagId})"));
if (users.Count == 0) return null;
var named = string.Join("; ", users.Take(NamedLimit));
var more = users.Count > NamedLimit ? $"; and {users.Count - NamedLimit} more" : string.Empty;
return $"This script is still used by {users.Count} item(s): {named}{more}. "
+ "Point them at another script or delete them first — a deployment would reject them otherwise.";
}
}
@@ -0,0 +1,31 @@
using System.ComponentModel.DataAnnotations;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
/// <summary>
/// Form-side guard for a name that becomes a UNS leaf NodeId segment (a VirtualTag <c>Name</c>): applies
/// <see cref="V3NodeIds.ValidateSegment"/>, the exact rule <see cref="V3NodeIds.Uns(string[])"/> enforces and the
/// deploy gate (<c>VirtualTagNameInvalid</c>) reports, so the modal refuses what publish would refuse — and only
/// that (lmxopcua#978, review C-1). Never restate the rule as a regex here: a second copy is how the editor and
/// the gate drifted apart in the first place.
/// </summary>
/// <remarks>
/// A null or empty value is left to <see cref="RequiredAttribute"/>, so a blank field shows one message, not two.
/// </remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public sealed class UnsLeafNameAttribute : ValidationAttribute
{
/// <inheritdoc />
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
if (value is not string text || text.Length == 0) return ValidationResult.Success;
var error = V3NodeIds.ValidateSegment(text);
if (error is null) return ValidationResult.Success;
var member = validationContext.MemberName is { } name ? new[] { name } : null;
return new ValidationResult(
$"{error} This name becomes part of the OPC UA NodeId, so it cannot contain '/' or start or end with a space.",
member);
}
}
@@ -1,6 +1,7 @@
using System.Security.Cryptography;
using System.Text;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
@@ -285,6 +286,13 @@ public sealed class UnsTreeService(
{
var normalized = string.IsNullOrWhiteSpace(displayNameOverride) ? null : displayNameOverride.Trim();
// lmxopcua#978 (review C-4): the override IS the UNS NodeId leaf — the same rule V3NodeIds.UnsChild throws
// on and the deploy gate reports as UnsEffectiveNameInvalid. Unchecked, a 'Temp/Inlet' saved, deployed
// green, and the composer silently dropped the variable.
if (normalized is not null && V3NodeIds.ValidateSegment(normalized) is { } segmentError)
return new UnsMutationResult(false,
$"Display name '{normalized}' cannot be used: {segmentError} It becomes part of the OPC UA NodeId.");
await using var db = await dbFactory.CreateDbContextAsync(ct);
var entity = await db.UnsTagReferences.FirstOrDefaultAsync(r => r.UnsTagReferenceId == unsTagReferenceId, ct);
@@ -1527,12 +1535,22 @@ public sealed class UnsTreeService(
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source)));
/// <summary>
/// Validates a virtual tag's script binding and trigger configuration (mirrors the DbContext CHECK
/// constraints): a script must be chosen, at least one of change-trigger / timer must be set, and a
/// Validates a virtual tag's name, script binding and trigger configuration (mirrors the deploy gate's
/// <c>VirtualTagNameInvalid</c> and the DbContext CHECK constraints): the name must be a legal UNS NodeId
/// segment, a script must be chosen, at least one of change-trigger / timer must be set, and a
/// set timer must be at least 50 ms. Returns <c>null</c> when the input is valid.
/// </summary>
private static UnsMutationResult? CheckVirtualTagRules(VirtualTagInput input)
{
// lmxopcua#978 (review C-1 ≡ R-5): the Name is the UNS NodeId leaf ({EquipmentId}/{Name}). Same rule as
// V3NodeIds.Uns and the deploy gate's VirtualTagNameInvalid — a 'Flow/Rate' or 'Speed ' used to save and
// seal, then throw in the address-space apply and VirtualTagHostActor on every node.
if (V3NodeIds.ValidateSegment(input.Name) is { } nameError)
{
return new UnsMutationResult(false,
$"Virtual tag name '{input.Name}' cannot be used: {nameError} It becomes part of the OPC UA NodeId.");
}
if (string.IsNullOrEmpty(input.ScriptId))
{
return new UnsMutationResult(false, "Pick a script.");
@@ -1116,7 +1116,17 @@ public sealed class AddressSpaceApplier
var parent = string.IsNullOrWhiteSpace(v.FolderPath)
? v.EquipmentId
: UnsSubFolder(v.EquipmentId, v.FolderPath);
var nodeId = UnsEquipmentVar(v.EquipmentId, v.FolderPath, v.Name);
string nodeId;
try { nodeId = UnsEquipmentVar(v.EquipmentId, v.FolderPath, v.Name); }
catch (ArgumentException ex)
{
// lmxopcua#978 (review C-1): an illegal name used to throw out of the whole materialise pass, so
// every VirtualTag after it was skipped and every later deploy failed at the same row. The deploy
// gate (VirtualTagNameInvalid) now rejects it; this skip-and-count is the backstop.
_logger.LogError("AddressSpaceApplier: VirtualTag {VirtualTagId} not materialised — {Reason}", v.VirtualTagId, ex.Message);
failed++;
continue;
}
// VirtualTags are computed outputs — read-only nodes (no inbound write).
if (!SafeEnsureVariable(nodeId, parent, v.Name, v.DataType, writable: false, realm: AddressSpaceRealm.Uns)) failed++;
}
@@ -116,7 +116,13 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
private void OnApply(ApplyVirtualTags msg)
{
Timers.Cancel("source-binding-retry");
var virtualIds = msg.Plans.Select(p => p.VirtualTagId).ToHashSet(StringComparer.Ordinal);
// lmxopcua#978 (review R-5): drop a plan whose NodeId cannot be built BEFORE anything is stopped or
// spawned. Unguarded, one illegal name threw here, supervision restarted the host (stopping every
// child), and nothing re-sent ApplyVirtualTags — every VirtualTag on the node stopped evaluating, on
// every deploy carrying the row. The deploy gate (VirtualTagNameInvalid) and authoring now refuse such
// a name; this is the backstop for an artifact that bypassed them.
var plans = WithoutUnbuildableNodeIds(msg.Plans);
var virtualIds = plans.Select(p => p.VirtualTagId).ToHashSet(StringComparer.Ordinal);
foreach (var id in _publishedVirtualIds.Where(id => !virtualIds.Contains(id)))
{
if (_virtualSourceIncarnations.Remove(id, out _)) _sourcePublisher?.RetireCurrentVirtual(id);
@@ -139,7 +145,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
// Only ENABLED plans are evaluated (lmxopcua#787). A disabled plan keeps its node (the applier
// materialises every plan) but gets no child: it is published BadOutOfService below. A plan flipped
// enabled->disabled drops out of `desired`, so its live child is stopped by the loop right after.
var evaluated = msg.Plans.Where(p => p.Enabled).ToList();
var evaluated = plans.Where(p => p.Enabled).ToList();
var newExpressions = evaluated.Select(p => p.Expression).ToHashSet(StringComparer.Ordinal);
var prevExpressions = _planByVtag.Values.Select(p => p.Expression).ToHashSet(StringComparer.Ordinal);
if (!newExpressions.SetEquals(prevExpressions))
@@ -271,7 +277,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
child.Tell(VirtualTagActor.ReassertValue.Instance);
}
RouteToDependents(msg.Plans);
RouteToDependents(plans);
// Disabled plans: never evaluated; publish BadOutOfService + null value on the (still present) UNS
// node, stamped at deploy time. Re-published on EVERY apply on purpose: a deploy that rebuilds the
@@ -281,7 +287,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
// exists to send a result for them.
// The same status is routed to the tag's dependents (lmxopcua#791), so a tag reading a disabled tag
// reports BadOutOfService instead of serving a value computed from a stale input.
foreach (var p in msg.Plans.Where(p => !p.Enabled))
foreach (var p in plans.Where(p => !p.Enabled))
{
if (_sourcePublisher is not null && !_virtualSourceIncarnations.ContainsKey(p.VirtualTagId))
{
@@ -301,7 +307,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
}
_log.Debug("VirtualTagHost: applied (desired={Desired}, children={Children}, disabled={Disabled})",
desired.Count, _children.Count, msg.Plans.Count - evaluated.Count);
desired.Count, _children.Count, plans.Count - evaluated.Count);
}
/// <summary>
@@ -392,6 +398,36 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
}
}
/// <summary>
/// The plans whose UNS NodeId <see cref="NodeIdFor"/> can build; each one it cannot (an illegal name or
/// folder segment — see <see cref="V3NodeIds.ValidateSegment"/>) is skipped and reported at Error, so one bad
/// row costs that tag alone rather than the whole host (lmxopcua#978, review R-5).
/// </summary>
/// <param name="plans">The plans as deployed.</param>
/// <returns>The plans that can be hosted, in their original order.</returns>
private IReadOnlyList<EquipmentVirtualTagPlan> WithoutUnbuildableNodeIds(IReadOnlyList<EquipmentVirtualTagPlan> plans)
{
List<EquipmentVirtualTagPlan>? kept = null;
for (var i = 0; i < plans.Count; i++)
{
var p = plans[i];
try
{
_ = NodeIdFor(p);
kept?.Add(p);
}
catch (ArgumentException ex)
{
kept ??= plans.Take(i).ToList();
_log.Error("VirtualTagHost: VirtualTag {VirtualTagId} (equipment {EquipmentId}) has a name that is not a " +
"legal UNS NodeId segment and is not hosted: {Reason}. The deploy gate (VirtualTagNameInvalid) " +
"should have rejected it; rename it and redeploy.",
p.VirtualTagId, p.EquipmentId, ex.Message);
}
}
return kept ?? plans;
}
/// <summary>UNS-realm NodeId for a VirtualTag plan — the equipment-anchored slash path
/// <c>{EquipmentId}[/{FolderPath}]/{Name}</c>, expressed through the v3 identity authority
/// <see cref="V3NodeIds.Uns(string[])"/>. Byte-identical to the applier's equipment-VirtualTag materialise
@@ -157,6 +157,15 @@ public sealed class DraftValidatorTests
BuildVirtualTag(equipmentId: rinser.EquipmentId, name: "oee"),
BuildVirtualTag(equipmentId: filler.EquipmentId, name: "throughput"),
],
// lmxopcua#978: a VirtualTag must reference a script that exists (VirtualTagScriptNotFound).
Scripts =
[
new Script
{
ScriptId = "s-1", Name = "line rate", SourceHash = "h-1",
SourceCode = "return (double)ctx.GetTag(\"Plant/Modbus/dev1/Speed\").Value;",
},
],
};
var errors = DraftValidator.Validate(draft);
@@ -0,0 +1,199 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#978 — the deploy-gate half of "one name authority + script gate" (review 2026-12-02 C-1 ≡ R-5,
/// C-4, C-7, C-2). Every name that becomes a UNS leaf NodeId segment is checked with the same
/// <see cref="V3NodeIds.ValidateSegment"/> rule <see cref="V3NodeIds.Uns(string[])"/> throws on, and every
/// VirtualTag / ScriptedAlarm must reference a script that exists.
/// </summary>
[Trait("Category", "Unit")]
public sealed class DraftValidatorUnsLeafNameAndScriptTests
{
private static Script ScriptRow(string id) => new()
{
ScriptId = id, Name = id, SourceCode = "return 1;", SourceHash = "h-" + id,
};
private static VirtualTag Vt(string name, string scriptId = "s1", string id = "vt-1") => new()
{
VirtualTagId = id, EquipmentId = "eq-1", Name = name, DataType = "Double", ScriptId = scriptId,
ChangeTriggered = true, TimerIntervalMs = 1000,
};
private static ScriptedAlarm Alarm(string predicateScriptId, bool enabled = true) => new()
{
ScriptedAlarmId = "al-1", EquipmentId = "eq-1", Name = "HighTemp", AlarmType = "LimitAlarm",
MessageTemplate = "hot", PredicateScriptId = predicateScriptId, Enabled = enabled,
};
private static Tag RawTag(string name = "raw-speed") => new()
{
TagId = "tag-1", DeviceId = "dev-1", Name = name, DataType = "Float",
AccessLevel = TagAccessLevel.Read, TagConfig = "{}",
};
private static UnsTagReference Ref(string? overrideName) => new()
{
UnsTagReferenceId = "ref-1", EquipmentId = "eq-1", TagId = "tag-1", DisplayNameOverride = overrideName,
};
// ----- C-1 / R-5: VirtualTag name -----
/// <summary>Each name the identity authority rejects is a deploy error, naming the VirtualTag.</summary>
[Theory]
[InlineData("a/b")]
[InlineData(" a")]
[InlineData("a ")]
[InlineData("a\n")]
[InlineData("")]
public void An_illegal_virtual_tag_name_is_rejected(string name)
{
// Premise: this is exactly a name the runtime would throw on.
Should.Throw<ArgumentException>(() => V3NodeIds.Uns("eq-1", name));
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
});
errors.ShouldHaveSingleItem().Code.ShouldBe(DraftValidator.VirtualTagNameInvalidCode);
errors[0].Context.ShouldBe("vt-1");
}
/// <summary>Positive control: a legal name (spaces inside, mixed case, dots) produces no error at all, so
/// the rule is not simply firing on every VirtualTag.</summary>
[Theory]
[InlineData("Flow Rate")]
[InlineData("speed.avg")]
[InlineData("_x")]
public void A_legal_virtual_tag_name_is_accepted(string name)
{
V3NodeIds.Uns("eq-1", name).ShouldBe("eq-1/" + name);
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt(name)], Scripts = [ScriptRow("s1")],
}).ShouldBeEmpty();
}
// ----- C-4: DisplayNameOverride -----
[Theory]
[InlineData("Temp/Inlet")]
[InlineData(" Temp")]
[InlineData("Temp ")]
public void An_illegal_display_name_override_is_rejected(string overrideName)
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
});
var error = errors.ShouldHaveSingleItem();
error.Code.ShouldBe(DraftValidator.UnsEffectiveNameInvalidCode);
error.Context.ShouldBe("ref-1");
}
/// <summary>Positive control: a legal override is accepted, and an empty/null one is not checked (the raw
/// tag's own name is RawNameInvalid's job).</summary>
[Theory]
[InlineData("Temp Inlet")]
[InlineData("")]
[InlineData(null)]
public void A_legal_or_absent_override_is_accepted(string? overrideName) =>
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", Tags = [RawTag()], UnsTagReferences = [Ref(overrideName)],
}).ShouldBeEmpty();
/// <summary>C-4 secondary: an EMPTY-string override means "use the raw tag name" at both compose seams, so
/// the gate must see the reference under that name — it used to skip it (<c>??</c> kept the empty string) and
/// miss the collision the composer then materialised.</summary>
[Fact]
public void An_empty_override_collides_under_the_backing_tag_name()
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
Tags = [RawTag("speed")],
UnsTagReferences = [Ref("")],
VirtualTags = [Vt("speed")],
Scripts = [ScriptRow("s1")],
});
errors.ShouldContain(e => e.Code == "UnsEffectiveNameCollision");
}
/// <summary>C-4 secondary, resolution side: an empty override resolves <c>{{equip}}/&lt;tag name&gt;</c>, as the
/// compose seams do.</summary>
[Fact]
public void An_empty_override_resolves_equip_references_under_the_backing_tag_name()
{
var script = new Script
{
ScriptId = "s1", Name = "s1", SourceHash = "h",
SourceCode = "return (double)ctx.GetTag(\"{{equip}}/speed\").Value;",
};
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
Tags = [RawTag("speed")],
UnsTagReferences = [Ref("")],
VirtualTags = [Vt("computed")],
Scripts = [script],
});
errors.ShouldNotContain(e => e.Code == "EquipReferenceUnresolved");
}
// ----- C-2: script existence -----
/// <summary>A timer-triggered VirtualTag whose script is gone — exactly the case that also passed
/// <c>VirtualTagNoEffectiveTrigger</c> — is a deploy error.</summary>
[Fact]
public void A_virtual_tag_with_a_missing_script_is_rejected()
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", VirtualTags = [Vt("computed", scriptId: "s-gone")], Scripts = [ScriptRow("s1")],
});
var error = errors.ShouldHaveSingleItem();
error.Code.ShouldBe(DraftValidator.VirtualTagScriptNotFoundCode);
error.Context.ShouldBe("vt-1");
error.Message.ShouldContain("s-gone");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_scripted_alarm_with_a_missing_predicate_is_rejected(bool enabled)
{
var errors = DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c", ScriptedAlarms = [Alarm("s-gone", enabled)], Scripts = [ScriptRow("s1")],
});
var error = errors.ShouldHaveSingleItem();
error.Code.ShouldBe(DraftValidator.ScriptedAlarmScriptNotFoundCode);
error.Context.ShouldBe("al-1");
error.Message.ShouldContain("s-gone");
}
/// <summary>Positive control: both rows referencing an existing script yield no error.</summary>
[Fact]
public void Rows_referencing_an_existing_script_are_accepted() =>
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
VirtualTags = [Vt("computed")],
ScriptedAlarms = [Alarm("s1")],
Scripts = [ScriptRow("s1")],
}).ShouldBeEmpty();
}
@@ -198,6 +198,42 @@ public sealed class ScriptEditLifecycleTests : BunitContext
cut.FindAll(".panel[role=alert]").ShouldBeEmpty();
using var db=_factory.CreateDbContext();db.Scripts.Any(x=>x.ScriptId=="a").ShouldBe(fail);db.Scripts.Any(x=>x.ScriptId=="b").ShouldBeTrue();
}
/// <summary>
/// lmxopcua#978 (review C-2): a script still used by a VirtualTag / ScriptedAlarm / Calculation tag is NOT
/// deleted, and the page names the user. It used to delete (no FK), and the next green deploy silently dropped
/// the scripted alarm. The unused script <c>b</c> deleting normally is the positive control.
/// </summary>
[Theory]
[InlineData("vtag")]
[InlineData("alarm")]
[InlineData("calc")]
public async Task A_script_in_use_is_not_deleted_and_the_user_is_named(string kind)
{
using(var seed=_factory.CreateUnintercepted())
{
if(kind=="vtag")seed.VirtualTags.Add(new VirtualTag{VirtualTagId="VT-1",EquipmentId="EQ-1",Name="oee",DataType="Double",ScriptId="a"});
if(kind=="alarm")seed.ScriptedAlarms.Add(new ScriptedAlarm{ScriptedAlarmId="AL-1",EquipmentId="EQ-1",Name="oee",AlarmType="LimitAlarm",MessageTemplate="m",PredicateScriptId="a"});
if(kind=="calc")seed.Tags.Add(new Tag{TagId="T-1",DeviceId="D-1",Name="oee",DataType="Double",AccessLevel=ZB.MOM.WW.OtOpcUa.Configuration.Enums.TagAccessLevel.Read,TagConfig="{\"scriptId\":\"a\"}"});
// Noise: the id appearing in an unrelated key must not block.
seed.Tags.Add(new Tag{TagId="T-2",DeviceId="D-1",Name="other",DataType="Double",AccessLevel=ZB.MOM.WW.OtOpcUa.Configuration.Enums.TagAccessLevel.Read,TagConfig="{\"note\":\"a\"}"});
seed.SaveChanges();
}
var cut=Open();cut.Find("button.btn-outline-danger").Click();
await cut.InvokeAsync(()=>cut.FindComponent<RawConfirmDialog>().Instance.OnConfirm.InvokeAsync());
using(var db=_factory.CreateDbContext())db.Scripts.Any(x=>x.ScriptId=="a").ShouldBeTrue();
var alert=cut.Find(".panel[role=alert]").TextContent;
alert.ShouldContain("Not deleted");
alert.ShouldContain(kind=="calc"?"T-1":kind=="alarm"?"AL-1":"VT-1");
alert.ShouldNotContain("T-2");
cut.FindComponent<RawConfirmDialog>().Instance.Visible.ShouldBeFalse();
Services.GetRequiredService<NavigationManager>().Uri.ShouldNotEndWith("/scripts");
// Positive control: the unused script deletes.
cut.Render(p=>p.Add(x=>x.ScriptId,"b"));cut.Find("button.btn-outline-danger").Click();
await cut.InvokeAsync(()=>cut.FindComponent<RawConfirmDialog>().Instance.OnConfirm.InvokeAsync());
using(var db=_factory.CreateDbContext())db.Scripts.Any(x=>x.ScriptId=="b").ShouldBeFalse();
}
private sealed class WriteGate:SaveChangesInterceptor
{
public bool Hold,Fail,Concurrency;public int Count;public byte[]? OriginalVersion;
@@ -219,6 +255,8 @@ public sealed class ScriptEditLifecycleTests : BunitContext
public readonly TaskCompletionSource Entered=new(TaskCreationOptions.RunContinuationsAsynchronously),Release=new(TaskCreationOptions.RunContinuationsAsynchronously);
public Factory(){using var db=CreateDbContext();db.Scripts.AddRange(new Script{ScriptId="a",Name="Alpha",SourceCode="return 1;",SourceHash="h1",RowVersion=[1,2]},new Script{ScriptId="b",Name="Beta",SourceCode="return 2;",SourceHash="h2",RowVersion=[3,4]});db.SaveChanges();}
public OtOpcUaConfigDbContext CreateDbContext()=>new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseInMemoryDatabase(_name).AddInterceptors(Writes).Options);
/// <summary>A context on the same store WITHOUT the write gate, for seeding non-Script rows.</summary>
public OtOpcUaConfigDbContext CreateUnintercepted()=>new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseInMemoryDatabase(_name).Options);
public async Task<OtOpcUaConfigDbContext> CreateDbContextAsync(CancellationToken cancellationToken=default)
{
if(Interlocked.Increment(ref Calls)==HoldAt){Entered.TrySetResult();await Release.Task.WaitAsync(cancellationToken);if(FailHeld)throw new InvalidOperationException("Synthetic load failure");}
@@ -0,0 +1,84 @@
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Uns;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// lmxopcua#978 (review C-1 ≡ R-5): the VirtualTag modal, the deploy gate and the runtime NodeId builder apply
/// ONE rule to a VirtualTag name — <see cref="V3NodeIds.ValidateSegment"/>. Editor accepts ⇔ publish accepts ⇔
/// the runtime can build the NodeId.
/// </summary>
[Trait("Category", "Unit")]
public sealed class UnsLeafNameAuthorityTests
{
private sealed class Model
{
[UnsLeafName] public string Name { get; set; } = "";
}
private static bool FormAccepts(string name)
{
var model = new Model { Name = name };
return Validator.TryValidateObject(model, new ValidationContext(model), new List<ValidationResult>(), validateAllProperties: true);
}
private static bool GateAccepts(string name) =>
!DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
VirtualTags =
[
new VirtualTag
{
VirtualTagId = "vt-1", EquipmentId = "eq-1", Name = name, DataType = "Double", ScriptId = "s1",
ChangeTriggered = true, TimerIntervalMs = 1000,
},
],
Scripts = [new Script { ScriptId = "s1", Name = "s1", SourceCode = "return 1;", SourceHash = "h" }],
}).Any(e => e.Code == DraftValidator.VirtualTagNameInvalidCode);
private static bool RuntimeBuilds(string name)
{
try { V3NodeIds.Uns("eq-1", name); return true; }
catch (ArgumentException) { return false; }
}
[Theory]
[InlineData("Flow/Rate", false)]
[InlineData("Speed ", false)]
[InlineData(" Speed", false)]
[InlineData("Speed\n", false)]
[InlineData("Flow Rate", true)]
[InlineData("speed.avg", true)]
[InlineData("OEE", true)]
public void The_modal_the_gate_and_the_runtime_agree(string name, bool legal)
{
FormAccepts(name).ShouldBe(legal);
GateAccepts(name).ShouldBe(legal);
RuntimeBuilds(name).ShouldBe(legal);
}
/// <summary>Blank is <see cref="RequiredAttribute"/>'s message, not a second one from this attribute.</summary>
[Fact]
public void A_blank_value_is_left_to_Required() => FormAccepts("").ShouldBeTrue();
/// <summary>The modal's form model actually carries the attribute (a guard on the wiring, which a test of the
/// attribute alone would not catch).</summary>
[Fact]
public void The_virtual_tag_modal_name_field_uses_the_authority()
{
var formModel = typeof(VirtualTagModal).GetNestedType("FormModel", BindingFlags.NonPublic);
formModel.ShouldNotBeNull();
var name = formModel!.GetProperty("Name");
name.ShouldNotBeNull();
name!.GetCustomAttribute<UnsLeafNameAttribute>().ShouldNotBeNull();
name.GetCustomAttribute<RequiredAttribute>().ShouldNotBeNull();
}
}
@@ -234,6 +234,8 @@ public sealed class UnsSegmentTests
[InlineData("line_1")]
[InlineData("")]
[InlineData("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")]
[InlineData("press-1\n")]
[InlineData("_default\n")]
public void The_attribute_pattern_agrees_with_IsValid(string candidate)
{
var byAttribute = System.Text.RegularExpressions.Regex.IsMatch(
@@ -254,4 +256,25 @@ public sealed class UnsSegmentTests
.IsMatch(UnsSegment.DefaultSegment, UnsSegment.Pattern).ShouldBeFalse();
UnsSegment.IsValid(UnsSegment.DefaultSegment).ShouldBeTrue();
}
/// <summary>
/// lmxopcua#978 (review C-7): <c>$</c> matches before a final <c>\n</c> in .NET, so a name with a trailing
/// newline (a quoted RFC-4180 CSV field) used to pass authoring and the deploy gate, then
/// <c>V3NodeIds.Uns</c> rejected it at apply and the equipment folder was silently dropped. Both patterns
/// and <see cref="UnsSegment.IsValid"/> must refuse it; the clean value is the positive control.
/// </summary>
[Theory]
[InlineData("press-1\n")]
[InlineData("press-1\r\n")]
[InlineData("\npress-1")]
[InlineData("_default\n")]
public void A_trailing_or_leading_newline_is_not_a_valid_segment(string candidate)
{
UnsSegment.IsValid(candidate).ShouldBeFalse();
System.Text.RegularExpressions.Regex.IsMatch(candidate, UnsSegment.Pattern).ShouldBeFalse();
System.Text.RegularExpressions.Regex.IsMatch(candidate, UnsSegment.AttributePattern).ShouldBeFalse();
var clean = candidate.Trim();
UnsSegment.IsValid(clean).ShouldBeTrue();
}
}
@@ -288,6 +288,32 @@ public sealed class UnsTreeServiceReferenceTests
guard.LastProposedName.ShouldBe("running");
}
/// <summary>
/// lmxopcua#978 (review C-4): an override is the UNS NodeId leaf, so one the identity authority rejects
/// ('/' inside — whitespace is trimmed away first) is refused at save, with the same rule the deploy gate's
/// <c>UnsEffectiveNameInvalid</c> applies. It used to save, deploy green, and vanish from the address space.
/// A legal override with an inner space is the positive control.
/// </summary>
[Theory]
[InlineData("Temp/Inlet", false)]
[InlineData("/", false)]
[InlineData("Temp Inlet", true)]
public async Task SetReferenceOverride_applies_the_uns_segment_rule(string overrideName, bool accepted)
{
var name = $"ref-override-segment-{Guid.NewGuid():N}";
Seed(name);
var service = new UnsTreeService(Factory(name));
await service.AddReferencesAsync(EquipmentId, ["TAG-speed"], TestContext.Current.CancellationToken);
var row = (await service.LoadReferencesForEquipmentAsync(EquipmentId, TestContext.Current.CancellationToken)).Single();
var result = await service.SetReferenceOverrideAsync(row.UnsTagReferenceId, overrideName, row.RowVersion, TestContext.Current.CancellationToken);
result.Ok.ShouldBe(accepted);
var after = (await service.LoadReferencesForEquipmentAsync(EquipmentId, TestContext.Current.CancellationToken)).Single();
after.DisplayNameOverride.ShouldBe(accepted ? overrideName : null);
if (!accepted) result.Error!.ShouldContain("'/'");
}
// ----- RemoveReference -----
/// <summary>Removing a reference deletes the row; a missing row is a no-op success.</summary>
@@ -181,6 +181,48 @@ public sealed class UnsTreeServiceVirtualTagTests
db.VirtualTags.Any(v => v.VirtualTagId == "VTAG-1").ShouldBeFalse();
}
/// <summary>
/// lmxopcua#978 (review C-1 ≡ R-5): the Name is the UNS NodeId leaf (<c>{EquipmentId}/{Name}</c>). A name the
/// identity authority throws on is refused at create — it used to save, seal, then throw in the address-space
/// apply and VirtualTagHostActor on every node. (<see cref="CreateVirtualTag_persists"/> is the positive control.)
/// </summary>
[Theory]
[InlineData("a/b")]
[InlineData(" a")]
[InlineData("a ")]
public async Task CreateVirtualTag_rejects_an_illegal_uns_name(string name)
{
var (service, dbName) = Fresh();
SeedEquipmentAndScript(dbName);
var result = await service.CreateVirtualTagAsync("EQ-1", Input("VTAG-1", name), TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Error!.ShouldContain("OPC UA NodeId");
using var db = UnsTreeTestDb.CreateNamed(dbName);
db.VirtualTags.Any().ShouldBeFalse();
}
/// <summary>lmxopcua#978: the same rule on rename — an existing tag cannot be renamed to an illegal name.</summary>
[Theory]
[InlineData("a/b")]
[InlineData("a ")]
public async Task UpdateVirtualTag_rejects_an_illegal_uns_name(string name)
{
var (service, dbName) = Fresh();
SeedEquipmentAndScript(dbName);
(await service.CreateVirtualTagAsync("EQ-1", Input("VTAG-1", "computed"), TestContext.Current.CancellationToken)).Ok.ShouldBeTrue();
byte[] rv;
using (var db = UnsTreeTestDb.CreateNamed(dbName))
rv = db.VirtualTags.Single(v => v.VirtualTagId == "VTAG-1").RowVersion;
var result = await service.UpdateVirtualTagAsync("VTAG-1", Input("VTAG-1", name), rv, TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
using var verify = UnsTreeTestDb.CreateNamed(dbName);
verify.VirtualTags.Single(v => v.VirtualTagId == "VTAG-1").Name.ShouldBe("computed");
}
// ----- UpdateVirtualTag -----
/// <summary>Updating a virtual tag changes its mutable fields and keeps EquipmentId.</summary>
@@ -107,6 +107,24 @@ public sealed class AddressSpaceApplierFailureSurfaceTests
applier.MaterialiseScriptedAlarms(alarms).ShouldBe(0);
}
/// <summary>
/// lmxopcua#978 (review C-1): a VirtualTag whose name the UNS identity authority rejects is skipped and
/// COUNTED as a failure (so the apply reports degraded), and the tags after it are still materialised. It used
/// to throw out of the whole pass, leaving every later VirtualTag unmaterialised on every deploy.
/// </summary>
[Fact]
public void An_illegal_virtual_tag_name_is_counted_and_the_rest_still_materialise()
{
var sink = new ConfigurableThrowingSink();
var applier = new AddressSpaceApplier(sink, NullLogger<AddressSpaceApplier>.Instance);
var vtags = CompositionWithVirtualTags(
new EquipmentVirtualTagPlan("v1", "eq-1", FolderPath: "", Name: "A/B", DataType: "Float", Expression: "1", DependencyRefs: Array.Empty<string>(), Historize: false),
new EquipmentVirtualTagPlan("v2", "eq-1", FolderPath: "", Name: "VB", DataType: "Float", Expression: "1", DependencyRefs: Array.Empty<string>(), Historize: false));
applier.MaterialiseEquipmentVirtualTags(vtags).ShouldBe(1);
sink.EnsuredVariables.ShouldContain("eq-1/VB");
}
// ---------------- fixtures ----------------
private static RawTagPlan RawTag(string id, string name) =>
@@ -204,8 +222,12 @@ public sealed class AddressSpaceApplierFailureSurfaceTests
public void EnsureVariable(string variableNodeId, string? parentFolderNodeId, string displayName, string dataType, bool writable, AddressSpaceRealm realm, string? historianTagname = null, bool isArray = false, uint? arrayLength = null, bool refuseArrayOnScalar = false)
{
if (ThrowOnEnsureVariable) throw new InvalidOperationException("simulated EnsureVariable fault");
EnsuredVariables.Add(variableNodeId);
}
/// <summary>Every variable NodeId <see cref="EnsureVariable"/> accepted, in call order.</summary>
public List<string> EnsuredVariables { get; } = new();
public void RebuildAddressSpace()
{
if (ThrowOnRebuild) throw new InvalidOperationException("simulated RebuildAddressSpace fault");
@@ -716,6 +716,48 @@ public sealed class VirtualTagHostActorTests : RuntimeActorTestBase
/// <summary>Deterministic no-op evaluator: keeps spawned children inert so tests drive the host's
/// OnResult path directly via synthetic EvaluationResults.</summary>
/// <summary>
/// lmxopcua#978 (review R-5): a plan whose name the UNS identity authority rejects is skipped, and the rest of
/// the apply still runs. It used to throw inside <c>OnApply</c>; supervision restarted the host (stopping every
/// child) and nothing re-sent the apply, so every VirtualTag on the node went dark on every deploy carrying the
/// row. Positive control: the good tag's result is still bridged — which a restarted host (empty NodeId map)
/// would silently drop — and the host was never restarted or stopped.
/// </summary>
[Theory]
[InlineData("A/B", true)]
[InlineData("Temp ", true)]
[InlineData("A/B", false)]
public void An_illegal_name_is_skipped_and_the_good_tags_keep_working(string badName, bool badEnabled)
{
var publish = CreateTestProbe();
var mux = CreateTestProbe();
var host = Sys.ActorOf(VirtualTagHostActor.Props(publish.Ref, mux.Ref, new StubEvaluator()));
var watcher = CreateTestProbe();
watcher.Watch(host);
var good = Plan("vt-good", "eq-1", "speed");
var bad = Plan("vt-bad", "eq-1", badName) with { Enabled = badEnabled };
host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { bad, good }));
// The good child spawned (its PreStart registration reaches the mux)...
mux.FishForMessage<DependencyMuxActor.RegisterInterest>(_ => true, cancellationToken: TestContext.Current.CancellationToken);
// ...and a second apply carrying the same bad row does not disturb it either.
host.Tell(new VirtualTagHostActor.ApplyVirtualTags(new[] { bad, good }));
var ts = new DateTime(2026, 12, 3, 12, 0, 0, DateTimeKind.Utc);
host.Tell(new VirtualTagActor.EvaluationResult("vt-good", 7.0, ts, CorrelationId.NewId()));
var update = publish.FishForMessage<OpcUaPublishActor.AttributeValueUpdate>(
u => u.TimestampUtc == ts, cancellationToken: TestContext.Current.CancellationToken);
update.NodeId.ShouldBe("eq-1/speed");
update.Value.ShouldBe(7.0);
// Nothing is ever published for the bad row (it has no buildable NodeId), and the host is alive.
host.Tell(new VirtualTagActor.EvaluationResult("vt-bad", 1.0, ts.AddSeconds(1), CorrelationId.NewId()));
publish.ExpectNoMsg(TimeSpan.FromMilliseconds(300), TestContext.Current.CancellationToken);
watcher.ExpectNoMsg(TimeSpan.FromMilliseconds(100), TestContext.Current.CancellationToken);
}
private sealed class StubEvaluator : IVirtualTagEvaluator
{
/// <summary>Returns NoChange so the child never emits on its own.</summary>