perf(adminui): one guard round-trip per bulk reference add

This commit is contained in:
Joseph Doherty
2026-08-16 04:03:49 -04:00
parent 541a223b96
commit fa36d64e8f
5 changed files with 251 additions and 28 deletions
@@ -12,8 +12,11 @@ namespace ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
/// <c>DraftValidator</c> <c>UnsEffectiveNameCollision</c> rule.
/// </summary>
/// <remarks>
/// Each call creates and disposes its own pooled context — the same per-call pattern
/// <see cref="UnsTreeService"/> uses — so the guard is safe to register <c>Scoped</c>.
/// Each call creates and disposes its own context — the same per-call pattern
/// <see cref="UnsTreeService"/> uses — so the guard is safe to register <c>Scoped</c>. The factory
/// really is pooled: <c>ServiceCollectionExtensions.AddOtOpcUaConfigDb</c> registers it with
/// <c>AddPooledDbContextFactory</c>, so the per-call create rents from the pool and the dispose
/// returns the context to it.
/// </remarks>
public sealed class EffectiveNameGuard(IDbContextFactory<OtOpcUaConfigDbContext> dbFactory) : IEffectiveNameGuard
{
@@ -27,6 +30,48 @@ public sealed class EffectiveNameGuard(IDbContextFactory<OtOpcUaConfigDbContext>
{
await using var db = await dbFactory.CreateDbContextAsync(ct);
var nameSpace = await LoadNameSpaceAsync(db, equipmentId, ct);
return FirstCollision(nameSpace, proposedEffectiveName, kind, excludeSourceId, equipmentId);
}
/// <inheritdoc />
/// <remarks>
/// The whole point of the batch entry point: ONE context and ONE load of the equipment's name
/// space, then every proposed name tested in memory against it — the per-name rules and message
/// text come from the same <see cref="FirstCollision"/> helper <see cref="CheckAsync"/> uses, so
/// the two can never drift. A batch is a create of N new rows, so there is no self-row to exclude.
/// </remarks>
public async Task<string?> CheckManyAsync(
string equipmentId,
IReadOnlyList<string> proposedEffectiveNames,
EffectiveNameSourceKind kind,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(proposedEffectiveNames);
if (proposedEffectiveNames.Count == 0) return null;
await using var db = await dbFactory.CreateDbContextAsync(ct);
var nameSpace = await LoadNameSpaceAsync(db, equipmentId, ct);
foreach (var proposed in proposedEffectiveNames)
{
var collision = FirstCollision(nameSpace, proposed, kind, excludeSourceId: null, equipmentId);
if (collision is not null) return collision;
}
return null;
}
/// <summary>
/// Loads the equipment's current effective-name space as a flat, ordered row list: references
/// first (override else the backing raw tag's <c>Name</c>), then VirtualTags, then ScriptedAlarms
/// — the order <see cref="CheckAsync"/> has always reported collisions in.
/// </summary>
private static async Task<List<NameRow>> LoadNameSpaceAsync(
OtOpcUaConfigDbContext db, string equipmentId, CancellationToken ct)
{
// References for this equipment. The effective name is the display-name override else the
// backing raw tag's current Name, so the two sets (references + tags) are loaded and joined
// in memory — the per-equipment set is small and this mirrors the deploy rule exactly
@@ -46,47 +91,66 @@ public sealed class EffectiveNameGuard(IDbContextFactory<OtOpcUaConfigDbContext>
.GroupBy(t => t.TagId, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().Name, StringComparer.Ordinal);
foreach (var r in references)
{
if (IsSelf(EffectiveNameSourceKind.Reference, r.UnsTagReferenceId, kind, excludeSourceId))
continue;
var effective = r.DisplayNameOverride
?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
if (Collides(effective, proposedEffectiveName))
return Message(proposedEffectiveName, "reference", r.UnsTagReferenceId, equipmentId);
}
var virtualTags = await db.VirtualTags
.AsNoTracking()
.Where(v => v.EquipmentId == equipmentId)
.Select(v => new { v.VirtualTagId, v.Name })
.ToListAsync(ct);
foreach (var v in virtualTags)
{
if (IsSelf(EffectiveNameSourceKind.VirtualTag, v.VirtualTagId, kind, excludeSourceId))
continue;
if (Collides(v.Name, proposedEffectiveName))
return Message(proposedEffectiveName, "VirtualTag", v.VirtualTagId, equipmentId);
}
var scriptedAlarms = await db.ScriptedAlarms
.AsNoTracking()
.Where(a => a.EquipmentId == equipmentId)
.Select(a => new { a.ScriptedAlarmId, a.Name })
.ToListAsync(ct);
foreach (var a in scriptedAlarms)
var rows = new List<NameRow>(references.Count + virtualTags.Count + scriptedAlarms.Count);
foreach (var r in references)
{
if (IsSelf(EffectiveNameSourceKind.ScriptedAlarm, a.ScriptedAlarmId, kind, excludeSourceId))
continue;
if (Collides(a.Name, proposedEffectiveName))
return Message(proposedEffectiveName, "ScriptedAlarm", a.ScriptedAlarmId, equipmentId);
var effective = r.DisplayNameOverride
?? (tagNameById.TryGetValue(r.TagId, out var n) ? n : null);
rows.Add(new NameRow(EffectiveNameSourceKind.Reference, r.UnsTagReferenceId, effective, "reference"));
}
foreach (var v in virtualTags)
rows.Add(new NameRow(EffectiveNameSourceKind.VirtualTag, v.VirtualTagId, v.Name, "VirtualTag"));
foreach (var a in scriptedAlarms)
rows.Add(new NameRow(EffectiveNameSourceKind.ScriptedAlarm, a.ScriptedAlarmId, a.Name, "ScriptedAlarm"));
return rows;
}
/// <summary>
/// The single in-memory collision rule shared by <see cref="CheckAsync"/> and
/// <see cref="CheckManyAsync"/> — same self-row exclusion, same ordinal comparison, same message.
/// </summary>
private static string? FirstCollision(
List<NameRow> nameSpace,
string proposedEffectiveName,
EffectiveNameSourceKind kind,
string? excludeSourceId,
string equipmentId)
{
foreach (var row in nameSpace)
{
if (IsSelf(row.Kind, row.SourceId, kind, excludeSourceId)) continue;
if (Collides(row.EffectiveName, proposedEffectiveName))
return Message(proposedEffectiveName, row.SourceLabel, row.SourceId, equipmentId);
}
return null;
}
/// <summary>One existing effective-name-space row: what it is, its logical id, its effective name
/// (null when a reference's backing tag is missing — such a row contributes no name), and the label
/// the collision message uses.</summary>
private readonly record struct NameRow(
EffectiveNameSourceKind Kind,
string SourceId,
string? EffectiveName,
string SourceLabel);
/// <summary>True when a row is the self-row being edited — same kind AND same logical id — so it
/// is excluded from the collision set (a rename / override-change of a row cannot collide with itself).</summary>
private static bool IsSelf(
@@ -58,4 +58,38 @@ public interface IEffectiveNameGuard
EffectiveNameSourceKind kind,
string? excludeSourceId,
CancellationToken ct = default);
/// <summary>
/// Checks many proposed names against ONE load of the equipment's name space. Returns the first
/// collision message (in input order), or <see langword="null"/> when all are free.
/// </summary>
/// <remarks>
/// The bulk-authoring entry point (a select-all "add references" over N raw tags), where the
/// per-name <see cref="CheckAsync"/> would cost N contexts × 4 queries. There is no
/// <c>excludeSourceId</c>: a batch is a CREATE of N new rows, so no self-row exists to exclude.
/// The default implementation simply loops <see cref="CheckAsync"/> — correct but not fast — so
/// a stub / no-op guard needs no change; <c>EffectiveNameGuard</c> overrides it with the
/// single-load version.
/// </remarks>
/// <param name="equipmentId">The owning equipment's logical id.</param>
/// <param name="proposedEffectiveNames">The effective names to be authored, in the order the caller wants them reported.</param>
/// <param name="kind">Which surface the proposed names are for (words the error; identifies the self-row kind).</param>
/// <param name="ct">Cancellation token.</param>
/// <returns><see langword="null"/> when every name is free; otherwise the first name's readable error.</returns>
async Task<string?> CheckManyAsync(
string equipmentId,
IReadOnlyList<string> proposedEffectiveNames,
EffectiveNameSourceKind kind,
CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(proposedEffectiveNames);
foreach (var proposed in proposedEffectiveNames)
{
var collision = await CheckAsync(equipmentId, proposed, kind, excludeSourceId: null, ct);
if (collision is not null) return collision;
}
return null;
}
}
@@ -209,6 +209,11 @@ public sealed class UnsTreeService(
// Track effective names proposed within THIS batch so two raw tags sharing a Name are caught (the
// guard sees only persisted rows; a same-batch collision would otherwise slip through).
var batchNames = new HashSet<string>(StringComparer.Ordinal);
// The proposed effective names, in selection order, for the ONE post-loop guard round-trip. The
// per-name guard call used to sit inside this loop, costing a fresh context + 4 queries per
// selected tag (a select-all of 500 tags ≈ 2,000 queries); the batch check loads the equipment's
// name space once and reports the first collision in this same order.
var proposedNames = new List<string>(distinctTagIds.Count);
var pending = new List<UnsTagReference>();
foreach (var tagId in distinctTagIds)
@@ -228,8 +233,7 @@ public sealed class UnsTreeService(
return new UnsMutationResult(false,
$"Two selected raw tags share the effective name '{tag.Name}'; set a display-name override so they stay unique within the equipment.");
var collision = await _guard.CheckAsync(equipmentId, tag.Name, EffectiveNameSourceKind.Reference, null, ct);
if (collision is not null) return new UnsMutationResult(false, collision);
proposedNames.Add(tag.Name);
pending.Add(new UnsTagReference
{
@@ -241,6 +245,12 @@ public sealed class UnsTreeService(
});
}
// One guard round-trip for the whole batch (one context + one load of the equipment's existing
// effective-name space), regardless of how many tags were selected.
var collision = await _guard.CheckManyAsync(
equipmentId, proposedNames, EffectiveNameSourceKind.Reference, ct);
if (collision is not null) return new UnsMutationResult(false, collision);
db.UnsTagReferences.AddRange(pending);
try
{