90de55535d
One migration, ScriptForeignKeysAndExternalIdUniqueness: - FK_VirtualTag_Script / FK_ScriptedAlarm_Script (Restrict) onto Script.ScriptId, which becomes NOT NULL and an alternate key (unique constraint UX_Script_LogicalId replaces the index). - UX_Equipment_ZTag / UX_Equipment_SAPID filtered UNIQUE indexes (blank = no identifier, the deploy gate's reading) replace the non-unique IX_ ones. - ExternalIdReservation + sp_ReleaseExternalIdReservation dropped (decision: retire — no writer since the generation model; uniqueness is gate + indexes). The /reservations page, query, ReservationKind, DraftSnapshot.ActiveReservations and the reservation pre-flight rule go too. - A read-only pre-check THROWs 51049 naming every offending row class (NULL ScriptId, dangling VirtualTag/ScriptedAlarm script, duplicated ZTag/SAPID, any reservation row) and changes nothing; Down restores the previous shape. Authoring mirrors so the constraints are never the first to say no: UnsTreeService refuses a missing script for VirtualTag/ScriptedAlarm create/update, and a ZTag/SAPID another equipment holds on create/update/import (owner named; import keeps the clean rows); values stored trimmed. ScriptEdit maps a concurrent-bind FK refusal to a message. Migration pre-check, Down round-trip, FK and index behaviour pinned against real SQL with positive controls.
170 lines
12 KiB
C#
170 lines
12 KiB
C#
using System.Data;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
|
|
|
/// <summary>
|
|
/// Materialises a <see cref="DraftSnapshot"/> from the live config DB so
|
|
/// <see cref="DraftValidator"/> can run against the current edit state at deploy time.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// This is a whole-DB ("global") snapshot — every cluster's rows in one pass — which is
|
|
/// what the deploy path needs: the admin-operations actor snapshots and flattens the
|
|
/// entire config, not one cluster. The validator's rules compare entity-level
|
|
/// <c>ClusterId</c> fields against each other (e.g. namespace binding), so the snapshot's
|
|
/// own <see cref="DraftSnapshot.ClusterId"/> is not read by any rule and is left empty.
|
|
/// </para>
|
|
/// <para>
|
|
/// <see cref="DraftSnapshot.GenerationId"/> is a placeholder (the generation model was
|
|
/// dropped); no rule reads it. (The prior-generation / path-length inputs
|
|
/// <c>PriorEquipment</c>, <c>Enterprise</c> and <c>Site</c> were removed with their never-firing rules,
|
|
/// lmxopcua#998 review C-10.)
|
|
/// </para>
|
|
/// <para>
|
|
/// <b>One consistent read.</b> On a relational provider the tables are read inside a
|
|
/// <see cref="IsolationLevel.Snapshot"/> transaction, so a <c>/uns</c> or <c>/raw</c> save that
|
|
/// lands mid-read cannot leave half the tables on the new state and half on the old. The deploy path
|
|
/// validates AND composes its artifact from this one snapshot, which is what makes "the artifact the
|
|
/// validator never saw" unrepresentable. SQL Server requires <c>ALLOW_SNAPSHOT_ISOLATION ON</c>
|
|
/// (migration <c>EnableSnapshotIsolation</c>); without it the first query fails with error 3952 and
|
|
/// the deploy is rejected rather than silently read unisolated. A non-relational provider (the
|
|
/// InMemory test provider) and a context already inside a transaction read without one — the
|
|
/// deploy compose opens its own SNAPSHOT transaction (it also writes the Deployment row in it). Do not
|
|
/// call this inside a SERIALIZABLE transaction: the read would range-lock every config table until
|
|
/// commit and deadlock with concurrent edits (lmxopcua#955).
|
|
/// </para>
|
|
/// </remarks>
|
|
public static class DraftSnapshotFactory
|
|
{
|
|
/// <summary>Builds a <see cref="DraftSnapshot"/> from the current config DB rows.</summary>
|
|
/// <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 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);
|
|
|
|
var ownsTransaction = db.Database.IsRelational() && db.Database.CurrentTransaction is null;
|
|
var tx = ownsTransaction
|
|
? await db.Database.BeginTransactionAsync(IsolationLevel.Snapshot, ct).ConfigureAwait(false)
|
|
: null;
|
|
await using (tx)
|
|
{
|
|
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),
|
|
};
|
|
}
|
|
|
|
// 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 —
|
|
// so the revision hash of an unchanged configuration is byte-identical across the refactor (fix round 1;
|
|
// pinned by ConfigComposerSqlServerHashStabilityTests). Re-sorting in memory with any other comparer would
|
|
// re-hash every mixed-case configuration and make drift detection report the whole fleet drifted.
|
|
private static async Task<DraftSnapshot> ReadAsync(OtOpcUaConfigDbContext db, CancellationToken ct)
|
|
=> new DraftSnapshot
|
|
{
|
|
// GenerationId=0 and null Enterprise/Site are intentional conservative fallbacks at the
|
|
// global-factory level: the path-length validator uses its upper bound, and cross-gen
|
|
// EquipmentUuid checks run in separate validator passes — no rule here reads these fields.
|
|
GenerationId = 0, // generation model dropped; placeholder (no rule reads it)
|
|
ClusterId = string.Empty, // global snapshot; rules compare entity ClusterId fields, not this
|
|
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),
|
|
// v3: Namespace entity retired — no namespace list to materialize. The Raw tree
|
|
// (RawFolders/TagGroups) + UnsTagReferences feed the v3 rules (charset, tagname length,
|
|
// effective-leaf uniqueness).
|
|
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 = await db.Tags.AsNoTracking().OrderBy(x => x.TagId).ToListAsync(ct),
|
|
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),
|
|
Scripts = await db.Scripts.AsNoTracking().OrderBy(x => x.ScriptId).ToListAsync(ct),
|
|
PollGroups = await db.PollGroups.AsNoTracking().OrderBy(x => x.PollGroupId).ToListAsync(ct),
|
|
NodeAcls = await db.NodeAcls.AsNoTracking().OrderBy(x => x.NodeAclId).ToListAsync(ct),
|
|
ApiKeys = await db.ApiKeys.AsNoTracking().OrderBy(x => x.ApiKeyId).ToListAsync(ct),
|
|
};
|
|
}
|