diff --git a/docs/Uns.md b/docs/Uns.md index 5cf060ffc..ffd5e38ed 100644 --- a/docs/Uns.md +++ b/docs/Uns.md @@ -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), diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 05845b0ad..c56a1efe7 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -299,6 +299,7 @@ Virtual-tag nodes are materialised by `AddressSpaceApplier` and fed by `VirtualT - **`{{equip}}/` 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)). diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/V3NodeIds.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/V3NodeIds.cs index 737396046..f64af4f11 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/V3NodeIds.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/OpcUa/V3NodeIds.cs @@ -67,6 +67,18 @@ public static class V3NodeIds // ----- Uns realm ----- + /// + /// The ONE rule for a UNS NodeId segment — exactly what and + /// enforce (non-empty, no , no leading/trailing + /// whitespace; delegated to ). Every authoring surface and deploy-gate + /// rule for a name that becomes a UNS leaf (a VirtualTag Name, a reference's effective name / + /// DisplayNameOverride) 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). + /// + /// The candidate segment. + /// A human-readable error when invalid, or when the segment is valid. + public static string? ValidateSegment(string? segment) => RawPaths.ValidateSegment(segment); + /// /// The UNS-namespace s= 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)); } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs index 2a6eeb3db..9dc797509 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentReferenceMap.cs @@ -30,6 +30,18 @@ public static class EquipmentReferenceMap /// The tag's owning tag-group id, or when directly under the device. public readonly record struct TagRow(string Name, string DeviceId, string? TagGroupId); + /// + /// The effective-name rule, stated once: the when it is non-empty, + /// else the backing raw tag's . An EMPTY override counts as "no override" — the + /// rule both compose seams apply; the deploy gate used ?? and so skipped an empty-string override + /// the composer materialised under the tag name (lmxopcua#978, review C-4). + /// + /// The reference's optional override. + /// The backing raw tag's Name, or when the tag is unknown. + /// The effective name, or when neither is available. + public static string? EffectiveName(string? displayNameOverride, string? tagName) => + string.IsNullOrEmpty(displayNameOverride) ? tagName : displayNameOverride; + /// /// Build the reference map. For each reference (ordered by UnsTagReferenceId), resolve the /// backing tag's RawPath via 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) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs index 78eb0aa9f..22bc451d5 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs @@ -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 } /// Extract the scriptId string from a calc tag's schemaless TagConfig JSON. Never - /// throws — malformed/blank/non-object JSON or an absent/non-string scriptId yields null. - private static string? ParseScriptId(string? tagConfig) + /// throws — malformed/blank/non-object JSON or an absent/non-string scriptId yields null. Public so the + /// AdminUI script-delete usage check reads the same key the gate does (lmxopcua#978). + /// The tag's TagConfig JSON. + /// The non-blank scriptId, or . + public static string? ParseScriptId(string? tagConfig) { if (string.IsNullOrWhiteSpace(tagConfig)) return null; try @@ -740,6 +746,86 @@ public static class DraftValidator } } + /// The VirtualTagNameInvalid error code (lmxopcua#978). + public const string VirtualTagNameInvalidCode = "VirtualTagNameInvalid"; + + /// The UnsEffectiveNameInvalid error code (lmxopcua#978). + public const string UnsEffectiveNameInvalidCode = "UnsEffectiveNameInvalid"; + + /// The VirtualTagScriptNotFound error code (lmxopcua#978). + public const string VirtualTagScriptNotFoundCode = "VirtualTagScriptNotFound"; + + /// The ScriptedAlarmScriptNotFound error code (lmxopcua#978). + public const string ScriptedAlarmScriptNotFoundCode = "ScriptedAlarmScriptNotFound"; + + /// + /// lmxopcua#978 (review C-1 ≡ R-5, C-4): every name that becomes a UNS leaf NodeId segment must pass + /// — the exact rule throws on. + /// + /// A VirtualTag's Name (its NodeId is {EquipmentId}/{Name}). Unchecked, a + /// Flow/Rate or "Speed " sealed, then threw in the address-space apply and in + /// VirtualTagHostActor on every node, on every later deploy. + /// A reference's non-empty DisplayNameOverride (its effective name). Unchecked, the composer + /// silently dropped the UNS variable. An empty override falls back to the raw tag name, which + /// RawNameInvalid already covers. + /// + /// The authoring surfaces (VirtualTag modal + service, the override editor) call the same method. + /// + private static void ValidateUnsLeafNames(DraftSnapshot draft, List 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)); + } + } + + /// + /// lmxopcua#978 (review C-2): every VirtualTag's ScriptId and every ScriptedAlarm's + /// PredicateScriptId 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. + /// + private static void ValidateScriptReferences(DraftSnapshot draft, List 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)); + } + } + /// 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 ({EquipmentId}/{EffectiveName}). @@ -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>(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(StringComparer.Ordinal); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/UnsSegment.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/UnsSegment.cs index 1a4478267..2f84efae3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/UnsSegment.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/UnsSegment.cs @@ -38,15 +38,18 @@ public static class UnsSegment /// ⚠️ This does not admit — an attribute cannot express the /// alternation and stay readable. is the one to put on a form; /// is the one to call in code. + /// ⚠️ Anchored with \A/\z, never ^/$: in .NET $ also matches before a + /// final \n, so "press-1\n" 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). /// - public const string Pattern = "^[a-z0-9-]{1,32}$"; + public const string Pattern = @"\A[a-z0-9-]{1,32}\z"; /// /// widened to admit — the form of the rule to /// put in a [RegularExpression] attribute, so the UI accepts exactly what the deploy gate /// accepts and no less. /// - public const string AttributePattern = "^([a-z0-9-]{1,32}|_default)$"; + public const string AttributePattern = @"\A(?:[a-z0-9-]{1,32}|_default)\z"; /// The message shown for a rejected segment, in the UI and from the service guards. public const string Message = diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor index b46605404..815db2549 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ScriptEdit.razor @@ -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() diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/VirtualTagModal.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/VirtualTagModal.razor index 7a7517e0a..84d4d22b7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/VirtualTagModal.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Uns/VirtualTagModal.razor @@ -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; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs index 19fae3e1e..afbcafeba 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/IScriptTagCatalog.cs @@ -144,7 +144,8 @@ public sealed class ScriptTagCatalog( var names = new HashSet(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!); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs new file mode 100644 index 000000000..a1d1709cb --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/ScriptUsage.cs @@ -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; + +/// +/// The script-delete usage check (lmxopcua#978, review C-2). VirtualTag.ScriptId, +/// ScriptedAlarm.PredicateScriptId and a Calculation tag's TagConfig.scriptId 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 +/// (VirtualTagScriptNotFound / ScriptedAlarmScriptNotFound / CalculationScriptNotFound); +/// this stops the delete that would create it, and says which rows hold the script. +/// +/// +/// 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 (Restrict) would close it but needs a migration. +/// +public static class ScriptUsage +{ + /// How many using rows are named in the refusal before it summarises the rest. + private const int NamedLimit = 5; + + /// + /// Describes every row that references , or returns when + /// nothing does and the script may be deleted. + /// + /// The context the delete will run on. + /// The script about to be deleted. + /// Cancellation token. + /// A refusal naming the users, or when the script is unused. + public static async Task DescribeBlockingUsageAsync( + OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(db); + ArgumentException.ThrowIfNullOrEmpty(scriptId); + + var users = new List(); + + 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."; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsLeafNameAttribute.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsLeafNameAttribute.cs new file mode 100644 index 000000000..6af9d2f63 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsLeafNameAttribute.cs @@ -0,0 +1,31 @@ +using System.ComponentModel.DataAnnotations; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns; + +/// +/// Form-side guard for a name that becomes a UNS leaf NodeId segment (a VirtualTag Name): applies +/// , the exact rule enforces and the +/// deploy gate (VirtualTagNameInvalid) 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. +/// +/// +/// A null or empty value is left to , so a blank field shows one message, not two. +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)] +public sealed class UnsLeafNameAttribute : ValidationAttribute +{ + /// + 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); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs index b27583e3d..edb1a713e 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Uns/UnsTreeService.cs @@ -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))); /// - /// 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 + /// VirtualTagNameInvalid 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 null when the input is valid. /// 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."); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs index cc87923f8..4e19d67f4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/AddressSpaceApplier.cs @@ -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++; } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs index 9c56679a5..03d889972 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/VirtualTags/VirtualTagHostActor.cs @@ -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); } /// @@ -392,6 +398,36 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers } } + /// + /// The plans whose UNS NodeId can build; each one it cannot (an illegal name or + /// folder segment — see ) is skipped and reported at Error, so one bad + /// row costs that tag alone rather than the whole host (lmxopcua#978, review R-5). + /// + /// The plans as deployed. + /// The plans that can be hosted, in their original order. + private IReadOnlyList WithoutUnbuildableNodeIds(IReadOnlyList plans) + { + List? 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; + } + /// UNS-realm NodeId for a VirtualTag plan — the equipment-anchored slash path /// {EquipmentId}[/{FolderPath}]/{Name}, expressed through the v3 identity authority /// . Byte-identical to the applier's equipment-VirtualTag materialise diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorTests.cs index ef2824603..6f090361e 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorTests.cs @@ -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); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorUnsLeafNameAndScriptTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorUnsLeafNameAndScriptTests.cs new file mode 100644 index 000000000..ff6cc5945 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorUnsLeafNameAndScriptTests.cs @@ -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; + +/// +/// 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 +/// rule throws on, and every +/// VirtualTag / ScriptedAlarm must reference a script that exists. +/// +[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 ----- + + /// Each name the identity authority rejects is a deploy error, naming the VirtualTag. + [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(() => 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"); + } + + /// 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. + [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"); + } + + /// 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). + [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(); + + /// 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 (?? kept the empty string) and + /// miss the collision the composer then materialised. + [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"); + } + + /// C-4 secondary, resolution side: an empty override resolves {{equip}}/<tag name>, as the + /// compose seams do. + [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 ----- + + /// A timer-triggered VirtualTag whose script is gone — exactly the case that also passed + /// VirtualTagNoEffectiveTrigger — is a deploy error. + [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"); + } + + /// Positive control: both rows referencing an existing script yield no error. + [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(); +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ScriptEditLifecycleTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ScriptEditLifecycleTests.cs index 7a3ef94e3..50e1ce92a 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ScriptEditLifecycleTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/ScriptEditLifecycleTests.cs @@ -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(); } + /// + /// 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 b deleting normally is the positive control. + /// + [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().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().Instance.Visible.ShouldBeFalse(); + Services.GetRequiredService().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().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().UseInMemoryDatabase(_name).AddInterceptors(Writes).Options); + /// A context on the same store WITHOUT the write gate, for seeding non-Script rows. + public OtOpcUaConfigDbContext CreateUnintercepted()=>new(new DbContextOptionsBuilder().UseInMemoryDatabase(_name).Options); public async Task 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");} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsLeafNameAuthorityTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsLeafNameAuthorityTests.cs new file mode 100644 index 000000000..0b6041cd0 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsLeafNameAuthorityTests.cs @@ -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; + +/// +/// 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 — . Editor accepts ⇔ publish accepts ⇔ +/// the runtime can build the NodeId. +/// +[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(), 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); + } + + /// Blank is 's message, not a second one from this attribute. + [Fact] + public void A_blank_value_is_left_to_Required() => FormAccepts("").ShouldBeTrue(); + + /// The modal's form model actually carries the attribute (a guard on the wiring, which a test of the + /// attribute alone would not catch). + [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().ShouldNotBeNull(); + name.GetCustomAttribute().ShouldNotBeNull(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsSegmentGuardTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsSegmentGuardTests.cs index 9a896c644..1317f1326 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsSegmentGuardTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsSegmentGuardTests.cs @@ -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(); } + + /// + /// lmxopcua#978 (review C-7): $ matches before a final \n in .NET, so a name with a trailing + /// newline (a quoted RFC-4180 CSV field) used to pass authoring and the deploy gate, then + /// V3NodeIds.Uns rejected it at apply and the equipment folder was silently dropped. Both patterns + /// and must refuse it; the clean value is the positive control. + /// + [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(); + } } diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceReferenceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceReferenceTests.cs index bf8df79f7..ae55b4785 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceReferenceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceReferenceTests.cs @@ -288,6 +288,32 @@ public sealed class UnsTreeServiceReferenceTests guard.LastProposedName.ShouldBe("running"); } + /// + /// 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 + /// UnsEffectiveNameInvalid applies. It used to save, deploy green, and vanish from the address space. + /// A legal override with an inner space is the positive control. + /// + [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 ----- /// Removing a reference deletes the row; a missing row is a no-op success. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceVirtualTagTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceVirtualTagTests.cs index 3354031c4..6f62706e7 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceVirtualTagTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Uns/UnsTreeServiceVirtualTagTests.cs @@ -181,6 +181,48 @@ public sealed class UnsTreeServiceVirtualTagTests db.VirtualTags.Any(v => v.VirtualTagId == "VTAG-1").ShouldBeFalse(); } + /// + /// lmxopcua#978 (review C-1 ≡ R-5): the Name is the UNS NodeId leaf ({EquipmentId}/{Name}). 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. ( is the positive control.) + /// + [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(); + } + + /// lmxopcua#978: the same rule on rename — an existing tag cannot be renamed to an illegal name. + [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 ----- /// Updating a virtual tag changes its mutable fields and keeps EquipmentId. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierFailureSurfaceTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierFailureSurfaceTests.cs index 1282a7316..c670e85d0 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierFailureSurfaceTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/AddressSpaceApplierFailureSurfaceTests.cs @@ -107,6 +107,24 @@ public sealed class AddressSpaceApplierFailureSurfaceTests applier.MaterialiseScriptedAlarms(alarms).ShouldBe(0); } + /// + /// 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. + /// + [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.Instance); + var vtags = CompositionWithVirtualTags( + new EquipmentVirtualTagPlan("v1", "eq-1", FolderPath: "", Name: "A/B", DataType: "Float", Expression: "1", DependencyRefs: Array.Empty(), Historize: false), + new EquipmentVirtualTagPlan("v2", "eq-1", FolderPath: "", Name: "VB", DataType: "Float", Expression: "1", DependencyRefs: Array.Empty(), 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); } + /// Every variable NodeId accepted, in call order. + public List EnsuredVariables { get; } = new(); + public void RebuildAddressSpace() { if (ThrowOnRebuild) throw new InvalidOperationException("simulated RebuildAddressSpace fault"); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagHostActorTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagHostActorTests.cs index 1205eb200..346fae504 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagHostActorTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/VirtualTags/VirtualTagHostActorTests.cs @@ -716,6 +716,48 @@ public sealed class VirtualTagHostActorTests : RuntimeActorTestBase /// Deterministic no-op evaluator: keeps spawned children inert so tests drive the host's /// OnResult path directly via synthetic EvaluationResults. + /// + /// 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 OnApply; 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. + /// + [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(_ => 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( + 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 { /// Returns NoChange so the child never emits on its own.