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:
@@ -67,6 +67,18 @@ public static class V3NodeIds
|
||||
|
||||
// ----- Uns realm -----
|
||||
|
||||
/// <summary>
|
||||
/// The ONE rule for a UNS NodeId segment — exactly what <see cref="Uns(string[])"/> and
|
||||
/// <see cref="UnsChild"/> enforce (non-empty, no <see cref="RawPaths.Separator"/>, no leading/trailing
|
||||
/// whitespace; delegated to <see cref="RawPaths.ValidateSegment"/>). Every authoring surface and deploy-gate
|
||||
/// rule for a name that becomes a UNS leaf (a VirtualTag <c>Name</c>, a reference's effective name /
|
||||
/// <c>DisplayNameOverride</c>) calls this, so the editor accepts exactly what the identity authority builds
|
||||
/// and no name can pass authoring and the gate only to throw at apply time (lmxopcua#978, review C-1/C-4).
|
||||
/// </summary>
|
||||
/// <param name="segment">The candidate segment.</param>
|
||||
/// <returns>A human-readable error when invalid, or <see langword="null"/> when the segment is valid.</returns>
|
||||
public static string? ValidateSegment(string? segment) => RawPaths.ValidateSegment(segment);
|
||||
|
||||
/// <summary>
|
||||
/// The UNS-namespace <c>s=</c> identifier for a folder or variable, slash-joined from
|
||||
/// ordered segments (Area, then Line, then Equipment, then an optional EffectiveName).
|
||||
@@ -94,7 +106,7 @@ public static class V3NodeIds
|
||||
public static string UnsChild(string parentUnsPath, string childSegment)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(parentUnsPath);
|
||||
var error = RawPaths.ValidateSegment(childSegment);
|
||||
var error = ValidateSegment(childSegment);
|
||||
if (error is not null)
|
||||
throw new ArgumentException($"Invalid UNS NodeId segment ('{childSegment}'): {error}", nameof(childSegment));
|
||||
|
||||
@@ -110,7 +122,7 @@ public static class V3NodeIds
|
||||
|
||||
for (var i = 0; i < list.Count; i++)
|
||||
{
|
||||
var error = RawPaths.ValidateSegment(list[i]);
|
||||
var error = ValidateSegment(list[i]);
|
||||
if (error is not null)
|
||||
throw new ArgumentException($"Invalid UNS NodeId segment at index {i} ('{list[i]}'): {error}", nameof(segments));
|
||||
}
|
||||
|
||||
@@ -30,6 +30,18 @@ public static class EquipmentReferenceMap
|
||||
/// <param name="TagGroupId">The tag's owning tag-group id, or <see langword="null"/> when directly under the device.</param>
|
||||
public readonly record struct TagRow(string Name, string DeviceId, string? TagGroupId);
|
||||
|
||||
/// <summary>
|
||||
/// The effective-name rule, stated once: the <paramref name="displayNameOverride"/> when it is non-empty,
|
||||
/// else the backing raw tag's <paramref name="tagName"/>. An EMPTY override counts as "no override" — the
|
||||
/// rule both compose seams apply; the deploy gate used <c>??</c> and so skipped an empty-string override
|
||||
/// the composer materialised under the tag name (lmxopcua#978, review C-4).
|
||||
/// </summary>
|
||||
/// <param name="displayNameOverride">The reference's optional override.</param>
|
||||
/// <param name="tagName">The backing raw tag's Name, or <see langword="null"/> when the tag is unknown.</param>
|
||||
/// <returns>The effective name, or <see langword="null"/> when neither is available.</returns>
|
||||
public static string? EffectiveName(string? displayNameOverride, string? tagName) =>
|
||||
string.IsNullOrEmpty(displayNameOverride) ? tagName : displayNameOverride;
|
||||
|
||||
/// <summary>
|
||||
/// Build the reference map. For each reference (ordered by <c>UnsTagReferenceId</c>), resolve the
|
||||
/// backing tag's RawPath via <paramref name="resolver"/> and key it under the effective name within
|
||||
@@ -55,7 +67,7 @@ public static class EquipmentReferenceMap
|
||||
{
|
||||
if (string.IsNullOrEmpty(r.EquipmentId) || string.IsNullOrEmpty(r.TagId)) continue;
|
||||
if (!tagsById.TryGetValue(r.TagId, out var tag)) continue;
|
||||
var effectiveName = string.IsNullOrEmpty(r.DisplayNameOverride) ? tag.Name : r.DisplayNameOverride!;
|
||||
var effectiveName = EffectiveName(r.DisplayNameOverride, tag.Name);
|
||||
if (string.IsNullOrEmpty(effectiveName)) continue;
|
||||
var rawPath = resolver.TryBuildTagPath(tag.DeviceId, tag.TagGroupId, tag.Name);
|
||||
if (rawPath is null) continue; // broken chain — dropped (deploy gate rejects invalid names)
|
||||
|
||||
@@ -38,8 +38,10 @@ public static class DraftValidator
|
||||
ValidateRawNameCharset(draft, errors);
|
||||
ValidateHistorizedTagnameLength(draft, errors);
|
||||
ValidateHistorianReadOnly(draft, errors);
|
||||
ValidateUnsLeafNames(draft, errors);
|
||||
ValidateUnsEffectiveLeafUniqueness(draft, errors);
|
||||
ValidateEquipReferenceResolution(draft, errors);
|
||||
ValidateScriptReferences(draft, errors);
|
||||
ValidateCalculationTags(draft, errors);
|
||||
ValidateVirtualTagTriggers(draft, errors);
|
||||
ValidateVirtualTagDependencyCycles(draft, errors);
|
||||
@@ -505,7 +507,8 @@ public static class DraftValidator
|
||||
if (!v.Enabled) continue;
|
||||
if (v.TimerIntervalMs is > 0) continue;
|
||||
var source = scriptSourceById.TryGetValue(v.ScriptId, out var s) ? s : null;
|
||||
// An unresolved script is reported elsewhere; with no source there are no reads to count.
|
||||
// An unresolved script is VirtualTagScriptNotFound (ValidateScriptReferences); with no source there
|
||||
// are no reads to count.
|
||||
if (v.ChangeTriggered && source is null) continue;
|
||||
if (v.ChangeTriggered && EquipmentScriptPaths.ExtractDependencyRefs(source).Count > 0) continue;
|
||||
errors.Add(new("VirtualTagNoEffectiveTrigger",
|
||||
@@ -644,8 +647,11 @@ public static class DraftValidator
|
||||
}
|
||||
|
||||
/// <summary>Extract the <c>scriptId</c> string from a calc tag's schemaless <c>TagConfig</c> JSON. Never
|
||||
/// throws — malformed/blank/non-object JSON or an absent/non-string <c>scriptId</c> yields null.</summary>
|
||||
private static string? ParseScriptId(string? tagConfig)
|
||||
/// throws — malformed/blank/non-object JSON or an absent/non-string <c>scriptId</c> yields null. Public so the
|
||||
/// AdminUI script-delete usage check reads the same key the gate does (lmxopcua#978).</summary>
|
||||
/// <param name="tagConfig">The tag's TagConfig JSON.</param>
|
||||
/// <returns>The non-blank <c>scriptId</c>, or <see langword="null"/>.</returns>
|
||||
public static string? ParseScriptId(string? tagConfig)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tagConfig)) return null;
|
||||
try
|
||||
@@ -740,6 +746,86 @@ public static class DraftValidator
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The <c>VirtualTagNameInvalid</c> error code (lmxopcua#978).</summary>
|
||||
public const string VirtualTagNameInvalidCode = "VirtualTagNameInvalid";
|
||||
|
||||
/// <summary>The <c>UnsEffectiveNameInvalid</c> error code (lmxopcua#978).</summary>
|
||||
public const string UnsEffectiveNameInvalidCode = "UnsEffectiveNameInvalid";
|
||||
|
||||
/// <summary>The <c>VirtualTagScriptNotFound</c> error code (lmxopcua#978).</summary>
|
||||
public const string VirtualTagScriptNotFoundCode = "VirtualTagScriptNotFound";
|
||||
|
||||
/// <summary>The <c>ScriptedAlarmScriptNotFound</c> error code (lmxopcua#978).</summary>
|
||||
public const string ScriptedAlarmScriptNotFoundCode = "ScriptedAlarmScriptNotFound";
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#978 (review C-1 ≡ R-5, C-4): every name that becomes a UNS leaf NodeId segment must pass
|
||||
/// <see cref="V3NodeIds.ValidateSegment"/> — the exact rule <see cref="V3NodeIds.Uns(string[])"/> throws on.
|
||||
/// <list type="bullet">
|
||||
/// <item>A VirtualTag's <c>Name</c> (its NodeId is <c>{EquipmentId}/{Name}</c>). Unchecked, a
|
||||
/// <c>Flow/Rate</c> or <c>"Speed "</c> sealed, then threw in the address-space apply and in
|
||||
/// <c>VirtualTagHostActor</c> on every node, on every later deploy.</item>
|
||||
/// <item>A reference's non-empty <c>DisplayNameOverride</c> (its effective name). Unchecked, the composer
|
||||
/// silently dropped the UNS variable. An empty override falls back to the raw tag name, which
|
||||
/// <c>RawNameInvalid</c> already covers.</item>
|
||||
/// </list>
|
||||
/// The authoring surfaces (VirtualTag modal + service, the override editor) call the same method.
|
||||
/// </summary>
|
||||
private static void ValidateUnsLeafNames(DraftSnapshot draft, List<ValidationError> errors)
|
||||
{
|
||||
foreach (var v in draft.VirtualTags)
|
||||
{
|
||||
var error = V3NodeIds.ValidateSegment(v.Name);
|
||||
if (error is not null)
|
||||
errors.Add(new(VirtualTagNameInvalidCode,
|
||||
$"VirtualTag '{v.VirtualTagId}' name '{v.Name}' is not a legal UNS NodeId segment: {error}",
|
||||
v.VirtualTagId));
|
||||
}
|
||||
|
||||
foreach (var r in draft.UnsTagReferences)
|
||||
{
|
||||
if (string.IsNullOrEmpty(r.DisplayNameOverride)) continue;
|
||||
var error = V3NodeIds.ValidateSegment(r.DisplayNameOverride);
|
||||
if (error is not null)
|
||||
errors.Add(new(UnsEffectiveNameInvalidCode,
|
||||
$"reference '{r.UnsTagReferenceId}' display-name override '{r.DisplayNameOverride}' is not a legal " +
|
||||
$"UNS NodeId segment: {error}",
|
||||
r.UnsTagReferenceId));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#978 (review C-2): every VirtualTag's <c>ScriptId</c> and every ScriptedAlarm's
|
||||
/// <c>PredicateScriptId</c> must name a script in the draft. The two columns carry no FK, a script delete
|
||||
/// used to have no usage check, and each downstream layer assumed another enforced it: the composer
|
||||
/// silently skipped a scripted alarm with a missing predicate (the condition vanished on a green deploy)
|
||||
/// and deployed a VirtualTag with an empty expression (Bad forever). Disabled rows are included — a
|
||||
/// dangling reference is a broken row whether or not it is evaluated today, and re-enabling it later must
|
||||
/// not be the first time anyone hears of it.
|
||||
/// </summary>
|
||||
private static void ValidateScriptReferences(DraftSnapshot draft, List<ValidationError> errors)
|
||||
{
|
||||
var scriptIds = draft.Scripts.Select(s => s.ScriptId).ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
foreach (var v in draft.VirtualTags)
|
||||
{
|
||||
if (scriptIds.Contains(v.ScriptId)) continue;
|
||||
errors.Add(new(VirtualTagScriptNotFoundCode,
|
||||
$"VirtualTag '{v.VirtualTagId}' references script '{v.ScriptId}', which does not exist in the draft; " +
|
||||
"pick an existing script or restore the deleted one",
|
||||
v.VirtualTagId));
|
||||
}
|
||||
|
||||
foreach (var a in draft.ScriptedAlarms)
|
||||
{
|
||||
if (scriptIds.Contains(a.PredicateScriptId)) continue;
|
||||
errors.Add(new(ScriptedAlarmScriptNotFoundCode,
|
||||
$"ScriptedAlarm '{a.ScriptedAlarmId}' references predicate script '{a.PredicateScriptId}', which does " +
|
||||
"not exist in the draft; pick an existing script or restore the deleted one",
|
||||
a.ScriptedAlarmId));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v3: within an equipment, the EFFECTIVE leaf name must be unique across its UnsTagReferences
|
||||
/// (DisplayNameOverride else the backing raw tag's Name), its VirtualTags (Name), and its ScriptedAlarms
|
||||
/// (Name) — the three share the equipment's UNS NodeId space (<c>{EquipmentId}/{EffectiveName}</c>).
|
||||
@@ -762,7 +848,8 @@ public static class DraftValidator
|
||||
|
||||
foreach (var r in draft.UnsTagReferences)
|
||||
{
|
||||
var effective = r.DisplayNameOverride ?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
|
||||
var effective = EquipmentReferenceMap.EffectiveName(
|
||||
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
|
||||
Add(r.EquipmentId, effective, $"reference '{r.UnsTagReferenceId}'");
|
||||
}
|
||||
foreach (var v in draft.VirtualTags)
|
||||
@@ -797,7 +884,8 @@ public static class DraftValidator
|
||||
var refNamesByEquip = new Dictionary<string, HashSet<string>>(StringComparer.Ordinal);
|
||||
foreach (var r in draft.UnsTagReferences)
|
||||
{
|
||||
var effective = r.DisplayNameOverride ?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
|
||||
var effective = EquipmentReferenceMap.EffectiveName(
|
||||
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
|
||||
if (string.IsNullOrEmpty(effective)) continue;
|
||||
if (!refNamesByEquip.TryGetValue(r.EquipmentId, out var set))
|
||||
refNamesByEquip[r.EquipmentId] = set = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
@@ -38,15 +38,18 @@ public static class UnsSegment
|
||||
/// ⚠️ This does <b>not</b> admit <see cref="DefaultSegment"/> — an attribute cannot express the
|
||||
/// alternation and stay readable. <see cref="AttributePattern"/> is the one to put on a form;
|
||||
/// <see cref="IsValid"/> is the one to call in code.
|
||||
/// <para>⚠️ Anchored with <c>\A</c>/<c>\z</c>, never <c>^</c>/<c>$</c>: in .NET <c>$</c> also matches before a
|
||||
/// final <c>\n</c>, so <c>"press-1\n"</c> passed — through equipment CSV import, then the deploy gate —
|
||||
/// and the applier dropped the equipment folder after a green deploy (lmxopcua#978, review C-7).</para>
|
||||
/// </remarks>
|
||||
public const string Pattern = "^[a-z0-9-]{1,32}$";
|
||||
public const string Pattern = @"\A[a-z0-9-]{1,32}\z";
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="Pattern"/> widened to admit <see cref="DefaultSegment"/> — the form of the rule to
|
||||
/// put in a <c>[RegularExpression]</c> attribute, so the UI accepts exactly what the deploy gate
|
||||
/// accepts and no less.
|
||||
/// </summary>
|
||||
public const string AttributePattern = "^([a-z0-9-]{1,32}|_default)$";
|
||||
public const string AttributePattern = @"\A(?:[a-z0-9-]{1,32}|_default)\z";
|
||||
|
||||
/// <summary>The message shown for a rejected segment, in the UI and from the service guards.</summary>
|
||||
public const string Message =
|
||||
|
||||
@@ -233,13 +233,24 @@ else
|
||||
var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == intent.Id);
|
||||
if (!Current(generation)) return;
|
||||
if (entity is null) { Nav.NavigateTo("/scripts"); return; }
|
||||
// lmxopcua#978 (review C-2): no FK protects a script in use, so refuse here and name the users —
|
||||
// a deleted predicate used to drop its scripted alarm silently on the next green deploy.
|
||||
var inUse = await ZB.MOM.WW.OtOpcUa.AdminUI.Uns.ScriptUsage.DescribeBlockingUsageAsync(db, intent.Id);
|
||||
if (!Current(generation)) return;
|
||||
if (inUse is not null)
|
||||
{
|
||||
// Close the confirmation so the page-level alert naming the users is what the operator sees.
|
||||
_confirmDeleteVisible = false; _deleteIntent = null; ++_confirmationEpoch;
|
||||
_error = $"Not deleted. {inUse}";
|
||||
return;
|
||||
}
|
||||
db.Entry(entity).Property(e => e.RowVersion).OriginalValue = intent.RowVersion;
|
||||
db.Scripts.Remove(entity);
|
||||
await db.SaveChangesAsync();
|
||||
if (Current(generation)) Nav.NavigateTo("/scripts");
|
||||
}
|
||||
catch (DbUpdateConcurrencyException) { if (Current(generation)) _error = "Another user changed this script while you were viewing it."; }
|
||||
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}. Likely because virtual tags or scripted alarms still reference this script — remove them first."; }
|
||||
catch (Exception ex) { if (Current(generation)) _error = $"Delete failed: {ex.Message}."; }
|
||||
finally { if (Current(generation)) _busy = false; }
|
||||
}
|
||||
public void Dispose()
|
||||
|
||||
@@ -480,7 +480,8 @@
|
||||
private sealed class FormModel
|
||||
{
|
||||
[Required, RegularExpression("^[A-Za-z0-9_-]+$")] public string VirtualTagId { get; set; } = "";
|
||||
[Required] public string Name { get; set; } = "";
|
||||
// lmxopcua#978: the Name is the UNS NodeId leaf ({EquipmentId}/{Name}) — same rule as the deploy gate.
|
||||
[Required, UnsLeafName] public string Name { get; set; } = "";
|
||||
public string DataType { get; set; } = "Double";
|
||||
[Required] public string ScriptId { get; set; } = "";
|
||||
public bool ChangeTriggered { get; set; } = true;
|
||||
|
||||
@@ -144,7 +144,8 @@ public sealed class ScriptTagCatalog(
|
||||
var names = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var r in refs)
|
||||
{
|
||||
var eff = r.DisplayNameOverride ?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
|
||||
var eff = EquipmentReferenceMap.EffectiveName(
|
||||
r.DisplayNameOverride, tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
|
||||
if (!string.IsNullOrEmpty(eff)) names.Add(eff!);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
|
||||
|
||||
/// <summary>
|
||||
/// The script-delete usage check (lmxopcua#978, review C-2). <c>VirtualTag.ScriptId</c>,
|
||||
/// <c>ScriptedAlarm.PredicateScriptId</c> and a Calculation tag's <c>TagConfig.scriptId</c> carry no FK, so
|
||||
/// a delete used to succeed against a script in use; the next deploy then silently dropped the scripted alarm
|
||||
/// (and deployed the VirtualTag with an empty expression). The deploy gate now refuses such a draft
|
||||
/// (<c>VirtualTagScriptNotFound</c> / <c>ScriptedAlarmScriptNotFound</c> / <c>CalculationScriptNotFound</c>);
|
||||
/// this stops the delete that would create it, and says which rows hold the script.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A check-then-delete is not serialised against a concurrent "bind a VirtualTag to this script" — the deploy
|
||||
/// gate is the backstop for that window. A real FK (<c>Restrict</c>) would close it but needs a migration.
|
||||
/// </remarks>
|
||||
public static class ScriptUsage
|
||||
{
|
||||
/// <summary>How many using rows are named in the refusal before it summarises the rest.</summary>
|
||||
private const int NamedLimit = 5;
|
||||
|
||||
/// <summary>
|
||||
/// Describes every row that references <paramref name="scriptId"/>, or returns <see langword="null"/> when
|
||||
/// nothing does and the script may be deleted.
|
||||
/// </summary>
|
||||
/// <param name="db">The context the delete will run on.</param>
|
||||
/// <param name="scriptId">The script about to be deleted.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A refusal naming the users, or <see langword="null"/> when the script is unused.</returns>
|
||||
public static async Task<string?> DescribeBlockingUsageAsync(
|
||||
OtOpcUaConfigDbContext db, string scriptId, CancellationToken ct = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
ArgumentException.ThrowIfNullOrEmpty(scriptId);
|
||||
|
||||
var users = new List<string>();
|
||||
|
||||
var vtags = await db.VirtualTags.AsNoTracking()
|
||||
.Where(v => v.ScriptId == scriptId)
|
||||
.OrderBy(v => v.VirtualTagId)
|
||||
.Select(v => new { v.VirtualTagId, v.Name, v.EquipmentId })
|
||||
.ToListAsync(ct);
|
||||
users.AddRange(vtags.Select(v => $"virtual tag '{v.Name}' ({v.VirtualTagId}) on equipment {v.EquipmentId}"));
|
||||
|
||||
var alarms = await db.ScriptedAlarms.AsNoTracking()
|
||||
.Where(a => a.PredicateScriptId == scriptId)
|
||||
.OrderBy(a => a.ScriptedAlarmId)
|
||||
.Select(a => new { a.ScriptedAlarmId, a.Name, a.EquipmentId })
|
||||
.ToListAsync(ct);
|
||||
users.AddRange(alarms.Select(a => $"scripted alarm '{a.Name}' ({a.ScriptedAlarmId}) on equipment {a.EquipmentId}"));
|
||||
|
||||
// Calculation tags hold the id inside schemaless JSON: narrow in SQL by substring, then confirm with the
|
||||
// same parser the deploy gate uses, so a script id that merely appears in another key never blocks.
|
||||
var calcCandidates = await db.Tags.AsNoTracking()
|
||||
.Where(t => t.TagConfig.Contains(scriptId))
|
||||
.OrderBy(t => t.TagId)
|
||||
.Select(t => new { t.TagId, t.Name, t.TagConfig })
|
||||
.ToListAsync(ct);
|
||||
users.AddRange(calcCandidates
|
||||
.Where(t => string.Equals(DraftValidator.ParseScriptId(t.TagConfig), scriptId, StringComparison.Ordinal))
|
||||
.Select(t => $"calculation tag '{t.Name}' ({t.TagId})"));
|
||||
|
||||
if (users.Count == 0) return null;
|
||||
|
||||
var named = string.Join("; ", users.Take(NamedLimit));
|
||||
var more = users.Count > NamedLimit ? $"; and {users.Count - NamedLimit} more" : string.Empty;
|
||||
return $"This script is still used by {users.Count} item(s): {named}{more}. "
|
||||
+ "Point them at another script or delete them first — a deployment would reject them otherwise.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
|
||||
|
||||
/// <summary>
|
||||
/// Form-side guard for a name that becomes a UNS leaf NodeId segment (a VirtualTag <c>Name</c>): applies
|
||||
/// <see cref="V3NodeIds.ValidateSegment"/>, the exact rule <see cref="V3NodeIds.Uns(string[])"/> enforces and the
|
||||
/// deploy gate (<c>VirtualTagNameInvalid</c>) reports, so the modal refuses what publish would refuse — and only
|
||||
/// that (lmxopcua#978, review C-1). Never restate the rule as a regex here: a second copy is how the editor and
|
||||
/// the gate drifted apart in the first place.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A null or empty value is left to <see cref="RequiredAttribute"/>, so a blank field shows one message, not two.
|
||||
/// </remarks>
|
||||
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
|
||||
public sealed class UnsLeafNameAttribute : ValidationAttribute
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
|
||||
{
|
||||
if (value is not string text || text.Length == 0) return ValidationResult.Success;
|
||||
var error = V3NodeIds.ValidateSegment(text);
|
||||
if (error is null) return ValidationResult.Success;
|
||||
|
||||
var member = validationContext.MemberName is { } name ? new[] { name } : null;
|
||||
return new ValidationResult(
|
||||
$"{error} This name becomes part of the OPC UA NodeId, so it cannot contain '/' or start or end with a space.",
|
||||
member);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Types;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
@@ -285,6 +286,13 @@ public sealed class UnsTreeService(
|
||||
{
|
||||
var normalized = string.IsNullOrWhiteSpace(displayNameOverride) ? null : displayNameOverride.Trim();
|
||||
|
||||
// lmxopcua#978 (review C-4): the override IS the UNS NodeId leaf — the same rule V3NodeIds.UnsChild throws
|
||||
// on and the deploy gate reports as UnsEffectiveNameInvalid. Unchecked, a 'Temp/Inlet' saved, deployed
|
||||
// green, and the composer silently dropped the variable.
|
||||
if (normalized is not null && V3NodeIds.ValidateSegment(normalized) is { } segmentError)
|
||||
return new UnsMutationResult(false,
|
||||
$"Display name '{normalized}' cannot be used: {segmentError} It becomes part of the OPC UA NodeId.");
|
||||
|
||||
await using var db = await dbFactory.CreateDbContextAsync(ct);
|
||||
|
||||
var entity = await db.UnsTagReferences.FirstOrDefaultAsync(r => r.UnsTagReferenceId == unsTagReferenceId, ct);
|
||||
@@ -1527,12 +1535,22 @@ public sealed class UnsTreeService(
|
||||
Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source)));
|
||||
|
||||
/// <summary>
|
||||
/// Validates a virtual tag's script binding and trigger configuration (mirrors the DbContext CHECK
|
||||
/// constraints): a script must be chosen, at least one of change-trigger / timer must be set, and a
|
||||
/// Validates a virtual tag's name, script binding and trigger configuration (mirrors the deploy gate's
|
||||
/// <c>VirtualTagNameInvalid</c> and the DbContext CHECK constraints): the name must be a legal UNS NodeId
|
||||
/// segment, a script must be chosen, at least one of change-trigger / timer must be set, and a
|
||||
/// set timer must be at least 50 ms. Returns <c>null</c> when the input is valid.
|
||||
/// </summary>
|
||||
private static UnsMutationResult? CheckVirtualTagRules(VirtualTagInput input)
|
||||
{
|
||||
// lmxopcua#978 (review C-1 ≡ R-5): the Name is the UNS NodeId leaf ({EquipmentId}/{Name}). Same rule as
|
||||
// V3NodeIds.Uns and the deploy gate's VirtualTagNameInvalid — a 'Flow/Rate' or 'Speed ' used to save and
|
||||
// seal, then throw in the address-space apply and VirtualTagHostActor on every node.
|
||||
if (V3NodeIds.ValidateSegment(input.Name) is { } nameError)
|
||||
{
|
||||
return new UnsMutationResult(false,
|
||||
$"Virtual tag name '{input.Name}' cannot be used: {nameError} It becomes part of the OPC UA NodeId.");
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(input.ScriptId))
|
||||
{
|
||||
return new UnsMutationResult(false, "Pick a script.");
|
||||
|
||||
@@ -1116,7 +1116,17 @@ public sealed class AddressSpaceApplier
|
||||
var parent = string.IsNullOrWhiteSpace(v.FolderPath)
|
||||
? v.EquipmentId
|
||||
: UnsSubFolder(v.EquipmentId, v.FolderPath);
|
||||
var nodeId = UnsEquipmentVar(v.EquipmentId, v.FolderPath, v.Name);
|
||||
string nodeId;
|
||||
try { nodeId = UnsEquipmentVar(v.EquipmentId, v.FolderPath, v.Name); }
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
// lmxopcua#978 (review C-1): an illegal name used to throw out of the whole materialise pass, so
|
||||
// every VirtualTag after it was skipped and every later deploy failed at the same row. The deploy
|
||||
// gate (VirtualTagNameInvalid) now rejects it; this skip-and-count is the backstop.
|
||||
_logger.LogError("AddressSpaceApplier: VirtualTag {VirtualTagId} not materialised — {Reason}", v.VirtualTagId, ex.Message);
|
||||
failed++;
|
||||
continue;
|
||||
}
|
||||
// VirtualTags are computed outputs — read-only nodes (no inbound write).
|
||||
if (!SafeEnsureVariable(nodeId, parent, v.Name, v.DataType, writable: false, realm: AddressSpaceRealm.Uns)) failed++;
|
||||
}
|
||||
|
||||
@@ -116,7 +116,13 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
private void OnApply(ApplyVirtualTags msg)
|
||||
{
|
||||
Timers.Cancel("source-binding-retry");
|
||||
var virtualIds = msg.Plans.Select(p => p.VirtualTagId).ToHashSet(StringComparer.Ordinal);
|
||||
// lmxopcua#978 (review R-5): drop a plan whose NodeId cannot be built BEFORE anything is stopped or
|
||||
// spawned. Unguarded, one illegal name threw here, supervision restarted the host (stopping every
|
||||
// child), and nothing re-sent ApplyVirtualTags — every VirtualTag on the node stopped evaluating, on
|
||||
// every deploy carrying the row. The deploy gate (VirtualTagNameInvalid) and authoring now refuse such
|
||||
// a name; this is the backstop for an artifact that bypassed them.
|
||||
var plans = WithoutUnbuildableNodeIds(msg.Plans);
|
||||
var virtualIds = plans.Select(p => p.VirtualTagId).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var id in _publishedVirtualIds.Where(id => !virtualIds.Contains(id)))
|
||||
{
|
||||
if (_virtualSourceIncarnations.Remove(id, out _)) _sourcePublisher?.RetireCurrentVirtual(id);
|
||||
@@ -139,7 +145,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
// Only ENABLED plans are evaluated (lmxopcua#787). A disabled plan keeps its node (the applier
|
||||
// materialises every plan) but gets no child: it is published BadOutOfService below. A plan flipped
|
||||
// enabled->disabled drops out of `desired`, so its live child is stopped by the loop right after.
|
||||
var evaluated = msg.Plans.Where(p => p.Enabled).ToList();
|
||||
var evaluated = plans.Where(p => p.Enabled).ToList();
|
||||
var newExpressions = evaluated.Select(p => p.Expression).ToHashSet(StringComparer.Ordinal);
|
||||
var prevExpressions = _planByVtag.Values.Select(p => p.Expression).ToHashSet(StringComparer.Ordinal);
|
||||
if (!newExpressions.SetEquals(prevExpressions))
|
||||
@@ -271,7 +277,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
child.Tell(VirtualTagActor.ReassertValue.Instance);
|
||||
}
|
||||
|
||||
RouteToDependents(msg.Plans);
|
||||
RouteToDependents(plans);
|
||||
|
||||
// Disabled plans: never evaluated; publish BadOutOfService + null value on the (still present) UNS
|
||||
// node, stamped at deploy time. Re-published on EVERY apply on purpose: a deploy that rebuilds the
|
||||
@@ -281,7 +287,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
// exists to send a result for them.
|
||||
// The same status is routed to the tag's dependents (lmxopcua#791), so a tag reading a disabled tag
|
||||
// reports BadOutOfService instead of serving a value computed from a stale input.
|
||||
foreach (var p in msg.Plans.Where(p => !p.Enabled))
|
||||
foreach (var p in plans.Where(p => !p.Enabled))
|
||||
{
|
||||
if (_sourcePublisher is not null && !_virtualSourceIncarnations.ContainsKey(p.VirtualTagId))
|
||||
{
|
||||
@@ -301,7 +307,7 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
|
||||
_log.Debug("VirtualTagHost: applied (desired={Desired}, children={Children}, disabled={Disabled})",
|
||||
desired.Count, _children.Count, msg.Plans.Count - evaluated.Count);
|
||||
desired.Count, _children.Count, plans.Count - evaluated.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -392,6 +398,36 @@ public sealed class VirtualTagHostActor : ReceiveActor, IWithTimers
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The plans whose UNS NodeId <see cref="NodeIdFor"/> can build; each one it cannot (an illegal name or
|
||||
/// folder segment — see <see cref="V3NodeIds.ValidateSegment"/>) is skipped and reported at Error, so one bad
|
||||
/// row costs that tag alone rather than the whole host (lmxopcua#978, review R-5).
|
||||
/// </summary>
|
||||
/// <param name="plans">The plans as deployed.</param>
|
||||
/// <returns>The plans that can be hosted, in their original order.</returns>
|
||||
private IReadOnlyList<EquipmentVirtualTagPlan> WithoutUnbuildableNodeIds(IReadOnlyList<EquipmentVirtualTagPlan> plans)
|
||||
{
|
||||
List<EquipmentVirtualTagPlan>? kept = null;
|
||||
for (var i = 0; i < plans.Count; i++)
|
||||
{
|
||||
var p = plans[i];
|
||||
try
|
||||
{
|
||||
_ = NodeIdFor(p);
|
||||
kept?.Add(p);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
kept ??= plans.Take(i).ToList();
|
||||
_log.Error("VirtualTagHost: VirtualTag {VirtualTagId} (equipment {EquipmentId}) has a name that is not a " +
|
||||
"legal UNS NodeId segment and is not hosted: {Reason}. The deploy gate (VirtualTagNameInvalid) " +
|
||||
"should have rejected it; rename it and redeploy.",
|
||||
p.VirtualTagId, p.EquipmentId, ex.Message);
|
||||
}
|
||||
}
|
||||
return kept ?? plans;
|
||||
}
|
||||
|
||||
/// <summary>UNS-realm NodeId for a VirtualTag plan — the equipment-anchored slash path
|
||||
/// <c>{EquipmentId}[/{FolderPath}]/{Name}</c>, expressed through the v3 identity authority
|
||||
/// <see cref="V3NodeIds.Uns(string[])"/>. Byte-identical to the applier's equipment-VirtualTag materialise
|
||||
|
||||
Reference in New Issue
Block a user