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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user