Merge #978: one UNS leaf-name authority (modal = service = deploy gate), script-existence gate + in-use delete guard, VirtualTagHost skips invalid tags

This commit is contained in:
Joseph Doherty
2026-12-03 10:28:50 -05:00
23 changed files with 814 additions and 21 deletions
@@ -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>