fix(perf): #996 Wave 4 — blob-free health probes, narrow data-connections load, off-thread coordinator acks + AdminOps audit, events page cap, capped reservations page

C-6: DeploymentQueries projects Deployment without ArtifactBlob (DbHealthProbe, readiness, ClusterOverview, DriverHost boot).
C-11/A-5: DraftSnapshotFactory.FromConfigDbForDataConnectionsAsync + one-parse-per-artifact LoadAppliedAsync + capped pickers.
H-6: ConfigPublishCoordinator persists acks off the actor thread (AckPersisted); deadline backlog kicked in parallel.
H-3: Restart/Reconnect reply = dispatch; ConfigEdit audit written off-mailbox, failure logged not surfaced.
U-6: ServerHistorian:MaxEventsPerRead (default 10000) pages HistoryReadEvents; advertised as MaxReturnEventValues.
A-8: /reservations active-only by default, projected, capped at 200.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 10:58:50 -05:00
parent b9955f6946
commit ea976ffa81
31 changed files with 1184 additions and 104 deletions
@@ -0,0 +1,56 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Queries;
/// <summary>
/// A <see cref="Deployment"/> row WITHOUT its <c>ArtifactBlob</c> (lmxopcua#996, review C-6). The blob is the
/// gzip of the whole fleet config (hundreds of KB to MBs); every reader that only needs the row's metadata
/// must project to this shape instead of materialising the entity.
/// </summary>
/// <param name="DeploymentId">Deployment id.</param>
/// <param name="RevisionHash">Artifact revision hash.</param>
/// <param name="Status">Deployment status.</param>
/// <param name="CreatedBy">Creator.</param>
/// <param name="CreatedAtUtc">Creation time.</param>
/// <param name="SealedAtUtc">Seal time, when sealed.</param>
/// <param name="FailureReason">Failure text, when failed.</param>
public sealed record DeploymentSummary(
Guid DeploymentId,
string RevisionHash,
DeploymentStatus Status,
string CreatedBy,
DateTime CreatedAtUtc,
DateTime? SealedAtUtc,
string? FailureReason);
/// <summary>
/// Blob-free <c>Deployment</c> queries shared by the DB health probe, the readiness check, the cluster overview
/// and the driver-host boot read. A plain <c>db.Deployments…ToList()</c> drags <c>ArtifactBlob</c> over the wire;
/// these projections cannot.
/// </summary>
public static class DeploymentQueries
{
/// <summary>
/// Liveness probe query: selects one <c>DeploymentId</c> (never the artifact blob). Used by the 5 s
/// <c>DbHealthProbeActor</c> tick and the <c>configdb</c> readiness check.
/// </summary>
/// <param name="db">The config database context.</param>
/// <returns>A query yielding at most one deployment id.</returns>
public static IQueryable<Guid> ProbeQuery(OtOpcUaConfigDbContext db) =>
db.Deployments.AsNoTracking().Select(d => d.DeploymentId).Take(1);
/// <summary>Projects a deployment query to <see cref="DeploymentSummary"/> (no blob).</summary>
/// <param name="deployments">The source query.</param>
/// <returns>The blob-free projection.</returns>
public static IQueryable<DeploymentSummary> ToSummary(this IQueryable<Deployment> deployments) =>
deployments.Select(d => new DeploymentSummary(
d.DeploymentId, d.RevisionHash, d.Status, d.CreatedBy, d.CreatedAtUtc, d.SealedAtUtc, d.FailureReason));
/// <summary>The newest deployment (by <c>CreatedAtUtc</c>) as a blob-free summary.</summary>
/// <param name="db">The config database context.</param>
/// <returns>A query yielding at most one summary.</returns>
public static IQueryable<DeploymentSummary> LatestSummary(OtOpcUaConfigDbContext db) =>
db.Deployments.AsNoTracking().OrderByDescending(d => d.CreatedAtUtc).ToSummary().Take(1);
}
@@ -0,0 +1,54 @@
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Queries;
/// <summary>One displayed <c>ExternalIdReservation</c> row (only the columns the /reservations page shows).</summary>
/// <param name="Kind">ZTag or SAPID.</param>
/// <param name="Value">The reserved external id.</param>
/// <param name="EquipmentUuid">Owning equipment.</param>
/// <param name="ClusterId">Cluster it was published in.</param>
/// <param name="ReleasedAt">When it was released, or null while active.</param>
public sealed record ReservationRow(ReservationKind Kind, string Value, Guid EquipmentUuid, string ClusterId, DateTime? ReleasedAt);
/// <summary>A bounded page of reservations plus the total matching the filter.</summary>
/// <param name="Rows">At most <c>pageSize</c> rows, ordered by kind then value.</param>
/// <param name="Total">All rows matching the filter (so the page can say "showing N of M").</param>
public sealed record ReservationPage(IReadOnlyList<ReservationRow> Rows, int Total);
/// <summary>
/// The /reservations page's read (lmxopcua#996, review A-8): active rows by default, projected to the displayed columns and
/// capped — the page used to render every row, released ones included, which accumulate for the life of the database.
/// </summary>
public static class ReservationListQuery
{
/// <summary>Rows shown per page (the cluster-audit page's size).</summary>
public const int DefaultPageSize = 200;
/// <summary>The filtered, ordered, projected query (exposed so a test can pin its SQL shape).</summary>
/// <param name="db">The config DB context.</param>
/// <param name="includeReleased">True to include released rows.</param>
/// <returns>The unbounded ordered projection.</returns>
public static IQueryable<ReservationRow> Query(OtOpcUaConfigDbContext db, bool includeReleased)
{
var rows = db.ExternalIdReservations.AsNoTracking().AsQueryable();
if (!includeReleased) rows = rows.Where(r => r.ReleasedAt == null);
return rows.OrderBy(r => r.Kind).ThenBy(r => r.Value)
.Select(r => new ReservationRow(r.Kind, r.Value, r.EquipmentUuid, r.ClusterId, r.ReleasedAt));
}
/// <summary>Loads one capped page and the total count for the filter.</summary>
/// <param name="db">The config DB context.</param>
/// <param name="includeReleased">True to include released rows.</param>
/// <param name="pageSize">Maximum rows returned.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The page and the total.</returns>
public static async Task<ReservationPage> LoadAsync(
OtOpcUaConfigDbContext db, bool includeReleased, int pageSize = DefaultPageSize, CancellationToken ct = default)
{
var query = Query(db, includeReleased);
var total = await query.CountAsync(ct);
var rows = await query.Take(pageSize).ToListAsync(ct);
return new ReservationPage(rows, total);
}
}
@@ -42,7 +42,45 @@ public static class DraftSnapshotFactory
/// <param name="db">The config DB context to read from.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A snapshot populated from the live DB, ready for <see cref="DraftValidator.Validate"/>.</returns>
public static async Task<DraftSnapshot> FromConfigDbAsync(OtOpcUaConfigDbContext db, CancellationToken ct = default)
public static Task<DraftSnapshot> FromConfigDbAsync(OtOpcUaConfigDbContext db, CancellationToken ct = default)
=> ReadInSnapshotAsync(db, ReadAsync, ct);
/// <summary>
/// Builds a NARROW <see cref="DraftSnapshot"/> for <see cref="DataConnectionValidator"/> and the data-connections
/// authoring page (lmxopcua#996, review C-11 / A-5). It skips every table that validator never reads (Scripts,
/// PollGroups, NodeAcls, ApiKeys, reservations) and projects <see cref="Entities.Tag"/> to id/device/group/name
/// with <c>TagConfig</c> kept ONLY for rows that could carry an alarm intent. It must NOT be fed to
/// <see cref="DraftValidator"/> or the artifact composer — those need the whole snapshot
/// (<see cref="FromConfigDbAsync"/>).
/// </summary>
/// <param name="db">The config DB context to read from.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>A snapshot sufficient for <see cref="DataConnectionValidator.Validate(DraftSnapshot)"/>.</returns>
public static Task<DraftSnapshot> FromConfigDbForDataConnectionsAsync(OtOpcUaConfigDbContext db, CancellationToken ct = default)
=> ReadInSnapshotAsync(db, ReadForDataConnectionsAsync, ct);
/// <summary>
/// The narrow tag projection used by <see cref="FromConfigDbForDataConnectionsAsync"/>: <c>TagConfig</c> is
/// selected only when it could contain an <c>alarm</c> intent (case-insensitive substring, or any JSON
/// <c>\u</c> escape that could spell it), else NULL. Exposed so a test can pin the generated SQL.
/// </summary>
/// <param name="db">The config DB context.</param>
/// <returns>The projection query.</returns>
public static IQueryable<NarrowTag> NarrowTags(OtOpcUaConfigDbContext db) =>
db.Tags.AsNoTracking().OrderBy(x => x.TagId).Select(x => new NarrowTag(
x.TagId, x.DeviceId, x.TagGroupId, x.Name,
x.TagConfig.Contains("alarm") || x.TagConfig.Contains("\\u") ? x.TagConfig : null));
/// <summary>A <see cref="Entities.Tag"/> reduced to what the data-connection rules read.</summary>
/// <param name="TagId">Tag id.</param>
/// <param name="DeviceId">Owning device.</param>
/// <param name="TagGroupId">Owning group, if any.</param>
/// <param name="Name">Tag name.</param>
/// <param name="TagConfig">Config JSON, only when it may carry an alarm intent.</param>
public sealed record NarrowTag(string TagId, string DeviceId, string? TagGroupId, string Name, string? TagConfig);
private static async Task<DraftSnapshot> ReadInSnapshotAsync(
OtOpcUaConfigDbContext db, Func<OtOpcUaConfigDbContext, CancellationToken, Task<DraftSnapshot>> read, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(db);
@@ -52,13 +90,45 @@ public static class DraftSnapshotFactory
: null;
await using (tx)
{
var snapshot = await ReadAsync(db, ct).ConfigureAwait(false);
var snapshot = await read(db, ct).ConfigureAwait(false);
// Read-only: committing releases the snapshot's version-store reservation; nothing was written.
if (tx is not null) await tx.CommitAsync(ct).ConfigureAwait(false);
return snapshot;
}
}
private static async Task<DraftSnapshot> ReadForDataConnectionsAsync(OtOpcUaConfigDbContext db, CancellationToken ct)
{
var tags = await NarrowTags(db).ToListAsync(ct);
return new DraftSnapshot
{
GenerationId = 0,
ClusterId = string.Empty,
ServerClusters = await db.ServerClusters.AsNoTracking().OrderBy(x => x.ClusterId).ToListAsync(ct),
ClusterNodes = await db.ClusterNodes.AsNoTracking().OrderBy(x => x.NodeId).ToListAsync(ct),
DataConnectionScopeVersion = await db.DataConnectionScopeStates.AsNoTracking().Where(x => x.Id == 1).Select(x => x.ScopeVersion).SingleOrDefaultAsync(ct),
DataConnections = await db.DataConnections.AsNoTracking().OrderBy(x => x.DataConnectionId).ToListAsync(ct),
DataExports = await db.DataExports.AsNoTracking().OrderBy(x => x.DataExportId).ToListAsync(ct),
RemoteNamespaceMappings = await db.RemoteNamespaceMappings.AsNoTracking().OrderBy(x => x.RemoteNamespaceMappingId).ToListAsync(ct),
RawFolders = await db.RawFolders.AsNoTracking().OrderBy(x => x.RawFolderId).ToListAsync(ct),
DriverInstances = await db.DriverInstances.AsNoTracking().OrderBy(x => x.DriverInstanceId).ToListAsync(ct),
Devices = await db.Devices.AsNoTracking().OrderBy(x => x.DeviceId).ToListAsync(ct),
TagGroups = await db.TagGroups.AsNoTracking().OrderBy(x => x.TagGroupId).ToListAsync(ct),
UnsAreas = await db.UnsAreas.AsNoTracking().OrderBy(x => x.UnsAreaId).ToListAsync(ct),
UnsLines = await db.UnsLines.AsNoTracking().OrderBy(x => x.UnsLineId).ToListAsync(ct),
Equipment = await db.Equipment.AsNoTracking().OrderBy(x => x.EquipmentId).ToListAsync(ct),
Tags = tags.ConvertAll(t => new Entities.Tag
{
TagId = t.TagId, DeviceId = t.DeviceId, TagGroupId = t.TagGroupId, Name = t.Name,
DataType = string.Empty, AccessLevel = default, TagConfig = t.TagConfig ?? "{}",
}),
UnsTagReferences = await db.UnsTagReferences.AsNoTracking().OrderBy(x => x.UnsTagReferenceId).ToListAsync(ct),
VirtualTags = await db.VirtualTags.AsNoTracking().OrderBy(x => x.VirtualTagId).ToListAsync(ct),
ScriptedAlarms = await db.ScriptedAlarms.AsNoTracking().OrderBy(x => x.ScriptedAlarmId).ToListAsync(ct),
PriorEquipment = [],
};
}
// Every composed table is read ORDERED BY ITS NATURAL KEY, server-side. That order IS the deployment
// artifact's order (ConfigComposer.Compose serialises the snapshot as given): it is exactly the order the
// pre-R03:3.2 composer's own queries produced — the database collation's, case-insensitive on SQL Server —