6cffffe673
One command, run from the NEW build against a ConfigDb BEFORE its migrations, that names every row the upgrade or the next deploy would refuse; exit 1 if any, 2 if unreachable / not v3. - migration:* — row-naming twins of the constraint-adding migrations' pre-checks (ConfigurationGapsIndexesAndRowVersions: duplicate NodeAcl / LdapGroupRoleMapping; ScriptForeignKeysAndExternalIdUniqueness: NULL ScriptId, dangling VT/alarm scripts, duplicate ZTag/SAPID, reservation rows). (#1021) - deploy-gate — DeployGateRules, the gate's rule pass now extracted from AdminOperationsActor so both run the same code: every DraftValidator rule incl. VirtualTagNameInvalid / UnsEffectiveNameInvalid / *ScriptNotFound (#1015) and SqlNamedQueryInvalid (#1058), topology, TagConfig inspection. - script-gate — DeployScriptGate through RoslynDeployScriptChecker, plus every unused stored script (Warning). (#1013) An older schema is read through this build's model: tables a pending migration creates map to a typed zero-row query, added columns are left out of the model (LegacySchemaTolerance). SNAPSHOT read when allowed. Logic in ControlPlane/Preflight (Roslyn-free); the console shell binds Roslyn. Real-SQL tests: an old-schema DB with every finding class (and nothing written), clean controls, NULL ScriptId -> SnapshotUnreadable, non-v3 refused. docs/v2/upgrade-preflight.md records the dev runs; production runs stay user-gated (wonder-box hold).
191 lines
11 KiB
C#
191 lines
11 KiB
C#
using Microsoft.Data.SqlClient;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
|
using ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
|
|
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
|
|
|
|
/// <summary>
|
|
/// lmxopcua#1013 / #1015 / #1021 / #1058: the read-only upgrade preflight against real SQL Server. A ConfigDb still
|
|
/// on an OLDER schema (pending migrations add tables and columns) is read through this build's model, and every row
|
|
/// a pending migration or the next deploy would refuse is named — with nothing written. Positive controls: a clean
|
|
/// database reports no blocking finding; a database that is not a v3 ConfigDb is refused, not guessed at.
|
|
/// </summary>
|
|
[Trait("Category", "SchemaCompliance")]
|
|
public sealed class UpgradePreflightSqlServerTests
|
|
{
|
|
/// <summary>Before the gRPC data-connection tables, the #998 RowVersion columns and the #1040/#1049 constraints.</summary>
|
|
private const string OldSchema = "20261022102459_EnableSnapshotIsolation";
|
|
|
|
private static readonly RoslynDeployScriptChecker Checker = new();
|
|
|
|
private static async Task ExecAsync(SqlServerTestDatabase sql, string text)
|
|
{
|
|
await using var conn = new SqlConnection(sql.ConnectionString);
|
|
await conn.OpenAsync(TestContext.Current.CancellationToken);
|
|
await using var cmd = conn.CreateCommand();
|
|
cmd.CommandText = text;
|
|
await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
|
|
}
|
|
|
|
private static async Task<long> RowCountAsync(SqlServerTestDatabase sql)
|
|
{
|
|
await using var conn = new SqlConnection(sql.ConnectionString);
|
|
await conn.OpenAsync(TestContext.Current.CancellationToken);
|
|
await using var cmd = conn.CreateCommand();
|
|
cmd.CommandText = "SELECT SUM(p.rows) FROM sys.partitions p JOIN sys.tables t ON t.object_id = p.object_id WHERE p.index_id IN (0, 1)";
|
|
return Convert.ToInt64(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken));
|
|
}
|
|
|
|
private static Equipment NewEquipment(string lineId, string name, string? zTag)
|
|
{
|
|
var uuid = Guid.NewGuid();
|
|
return new Equipment
|
|
{
|
|
EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = lineId, Name = name,
|
|
MachineCode = "mc-" + uuid.ToString("N"), ZTag = zTag,
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Every class of finding on one old-schema database: the migration pre-checks (#1021), the new VirtualTag /
|
|
/// script-reference / ZTag gate rules (#1015), the Sql named-query rule (#1058) and the script compile gate (#1013).
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task An_old_schema_database_is_read_and_every_blocking_row_is_named_without_writing()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var sql = new SqlServerTestDatabase(OldSchema);
|
|
|
|
// Rows the old schema allows and the new one refuses. ServerCluster / NodeAcl by SQL: this build's model has
|
|
// columns (RowVersion) the old tables do not.
|
|
await ExecAsync(sql, """
|
|
INSERT ServerCluster (ClusterId, Name, Enterprise, Site, NodeCount, RedundancyMode, Enabled, CreatedBy)
|
|
VALUES ('C1', 'Cluster one', 'zb', 's1', 1, 'None', 1, 't');
|
|
INSERT NodeAcl (NodeAclId, ClusterId, Principal, ScopeKind, ScopeId, PermissionFlags)
|
|
VALUES ('acl-1', 'C1', 'ops', 'Cluster', NULL, 1), ('acl-2', 'C1', 'ops', 'Cluster', NULL, 1);
|
|
INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy)
|
|
VALUES ('ZTag', 'ZT-OLD', NEWID(), 'C1', 't');
|
|
""");
|
|
await using (var db = sql.NewContext())
|
|
{
|
|
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = "C1", Name = "area" });
|
|
db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "line" });
|
|
var eq1 = NewEquipment("LINE-1", "press1", "ZT-1");
|
|
db.Equipment.AddRange(eq1, NewEquipment("LINE-1", "press2", "zt-1"));
|
|
db.Scripts.Add(new Script { ScriptId = "SC-ok", Name = "ok", SourceCode = "return 1;", SourceHash = new string('a', 64) });
|
|
db.Scripts.Add(new Script
|
|
{
|
|
ScriptId = "SC-file", Name = "reads a file", SourceHash = new string('b', 64),
|
|
SourceCode = "return System.IO.File.ReadAllText(\"c:/x\");",
|
|
});
|
|
db.VirtualTags.AddRange(
|
|
new VirtualTag { VirtualTagId = "VT-dangling", EquipmentId = eq1.EquipmentId, Name = "dangling", DataType = "Int32", ScriptId = "SC-gone" },
|
|
new VirtualTag { VirtualTagId = "VT-slash", EquipmentId = eq1.EquipmentId, Name = "a/b", DataType = "Int32", ScriptId = "SC-ok" },
|
|
new VirtualTag { VirtualTagId = "VT-file", EquipmentId = eq1.EquipmentId, Name = "file", DataType = "String", ScriptId = "SC-file" });
|
|
db.DriverInstances.Add(new DriverInstance
|
|
{
|
|
DriverInstanceId = "DRV-odbc", ClusterId = "C1", Name = "odbc", DriverType = "Sql",
|
|
DriverConfig = """{"provider":"Odbc","queries":{"line":{"sql":"SELECT v FROM t WHERE v ILIKE 'a%'"}}}""",
|
|
});
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
|
|
var before = await RowCountAsync(sql);
|
|
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct);
|
|
|
|
report.PendingMigrations.ShouldContain(m => m.EndsWith("_ConfigurationGapsIndexesAndRowVersions", StringComparison.Ordinal));
|
|
report.PendingMigrations.ShouldContain(m => m.EndsWith("_ScriptForeignKeysAndExternalIdUniqueness", StringComparison.Ordinal));
|
|
report.Findings.ShouldContain(f => f.Check == "schema" && f.Code == "ReadAsEmpty" && f.Message.Contains("DataConnection"));
|
|
|
|
void Blocking(string check, string code, string text) =>
|
|
report.Findings.ShouldContain(f => f.Check == check && f.Code == code && f.Severity == PreflightSeverity.Blocking && f.Message.Contains(text),
|
|
$"expected {check}/{code} naming '{text}'");
|
|
|
|
// #1021: the migrations' own pre-checks, row-named.
|
|
Blocking("migration:ConfigurationGapsIndexesAndRowVersions", "DuplicateNodeAcl", "acl-1, acl-2");
|
|
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "VirtualTagScriptDangling", "VT-dangling");
|
|
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "DuplicateZTag", "ZT-1");
|
|
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "ExternalIdReservationRows", "ZT-OLD");
|
|
// #1015: the new deploy-gate rules.
|
|
Blocking("deploy-gate", "VirtualTagScriptNotFound", "VT-dangling");
|
|
Blocking("deploy-gate", "VirtualTagNameInvalid", "VT-slash");
|
|
Blocking("deploy-gate", "BadDuplicateExternalIdentifier", "ZT-1");
|
|
// #1058: an Odbc named query that does not parse as T-SQL.
|
|
Blocking("deploy-gate", "SqlNamedQueryInvalid", "DRV-odbc");
|
|
// #1013: the sandbox analyzer over the scripts in use.
|
|
Blocking("script-gate", "ScriptCompileFailed", "SC-file");
|
|
report.HasBlocking.ShouldBeTrue();
|
|
|
|
// Read-only: nothing written, no migration applied.
|
|
(await RowCountAsync(sql)).ShouldBe(before);
|
|
await using var verify = sql.NewContext();
|
|
verify.Database.GetAppliedMigrations().Last().ShouldBe(OldSchema);
|
|
}
|
|
|
|
/// <summary>Positive control: a clean, current database has no blocking finding; an unused broken script is a Warning only.</summary>
|
|
[Fact]
|
|
public async Task A_clean_current_database_has_no_blocking_finding()
|
|
{
|
|
var ct = TestContext.Current.CancellationToken;
|
|
using var sql = new SqlServerTestDatabase();
|
|
await using (var db = sql.NewContext())
|
|
{
|
|
db.Scripts.Add(new Script { ScriptId = "SC-unused", Name = "unused", SourceHash = new string('c', 64), SourceCode = "this is not C#" });
|
|
await db.SaveChangesAsync(ct);
|
|
}
|
|
|
|
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct);
|
|
|
|
report.PendingMigrations.ShouldBeEmpty();
|
|
report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}")));
|
|
report.Findings.ShouldContain(f => f.Check == "deploy-gate" && f.Code == "Clean");
|
|
report.Findings.ShouldContain(f => f.Code == "UnusedScriptDoesNotCompile" && f.Severity == PreflightSeverity.Warning && f.Subject == "SC-unused");
|
|
}
|
|
|
|
/// <summary>Positive control for the migration pre-checks: an old schema with clean data reports each pending check Clean.</summary>
|
|
[Fact]
|
|
public async Task An_old_schema_database_with_clean_data_reports_the_migrations_will_apply()
|
|
{
|
|
using var sql = new SqlServerTestDatabase(OldSchema);
|
|
|
|
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken);
|
|
|
|
report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}")));
|
|
report.Findings.Count(f => f.Check.StartsWith("migration:", StringComparison.Ordinal) && f.Code == "Clean").ShouldBe(2);
|
|
}
|
|
|
|
/// <summary>
|
|
/// A NULL <c>Script.ScriptId</c> (legal in the old schema) is named by the migration pre-check, and the snapshot
|
|
/// this build cannot read is reported as Blocking instead of crashing the tool.
|
|
/// </summary>
|
|
[Fact]
|
|
public async Task A_null_script_id_is_named_and_the_unreadable_snapshot_is_reported()
|
|
{
|
|
using var sql = new SqlServerTestDatabase(OldSchema);
|
|
await ExecAsync(sql, "INSERT Script (ScriptId, Name, SourceCode, SourceHash, Language) VALUES (NULL, 'orphan', 'return 1;', 'h', 'CSharp')");
|
|
|
|
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken);
|
|
|
|
report.Findings.ShouldContain(f => f.Code == "ScriptIdNull" && f.Severity == PreflightSeverity.Blocking && f.Message.Contains("orphan"));
|
|
report.Findings.ShouldContain(f => f.Code == "SnapshotUnreadable" && f.Severity == PreflightSeverity.Blocking);
|
|
report.HasBlocking.ShouldBeTrue();
|
|
}
|
|
|
|
/// <summary>A database without the v3 migration history is refused, never checked against the wrong model.</summary>
|
|
[Fact]
|
|
public async Task A_database_that_is_not_a_v3_ConfigDb_is_refused()
|
|
{
|
|
using var sql = new SqlServerTestDatabase("0"); // created, nothing applied
|
|
|
|
var ex = await Should.ThrowAsync<PreflightUnsupportedException>(() =>
|
|
UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken));
|
|
ex.Message.ShouldContain("is not a v3 OtOpcUa ConfigDb");
|
|
}
|
|
}
|