Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs
T
Joseph Doherty 5aa7d24db6 test(sql): #1114 SQL test DB harnesses: 300 s migration / 60 s connect timeouts; retry once on a lost migration applock
Item 4: Configuration.Tests SchemaComplianceFixture + MigrationScratchDatabase
and AdminUI.Tests AdminUiSqlServerFixture get the same 300 s migration command /
60 s connect timeouts ControlPlane.Tests' SqlServerTestDatabase got in #1111.
(Server.Tests / Host.Tests have no SQL Server test-DB harness.)

Item 5: all three harnesses (and ControlPlane's) retry database creation ONCE
under a fresh database name when the migration fails with a lost
__EFMigrationsLock (SQL 1223, 'Cannot release the application lock ... not
currently held'), dropping the half-migrated database first. Any other failure
behaves as before. Recognition is unit-tested in ControlPlane.Tests.
2026-12-05 02:58:36 -05:00

135 lines
6.6 KiB
C#

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
/// <summary>
/// A migrated, throw-away config database on the central SQL Server, for the few ControlPlane behaviours
/// the InMemory provider cannot model (a SQL Server <c>DbUpdateException</c> names the WHOLE statement
/// batch; collation-ordered reads). Same server / credentials / env overrides as
/// <c>Configuration.Tests.SchemaComplianceFixture</c> (<c>OTOPCUA_CONFIG_TEST_SERVER</c>,
/// <c>OTOPCUA_CONFIG_TEST_SA_PASSWORD</c>; default the shared docker host's dev SA), and the same database
/// name shape, so that suite's 24 h orphan reaper also reclaims a database a killed run leaks here.
/// </summary>
public sealed class SqlServerTestDatabase : IDisposable
{
private const string DefaultServer = "10.100.0.35,14330";
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
/// <summary>Gets the connection string of the migrated database.</summary>
public string ConnectionString { get; private set; } = null!;
private string _databaseName = null!;
/// <summary>Connection-open budget: the shared docker host is often heavily loaded (#1111).</summary>
private const int ConnectTimeoutSeconds = 60;
/// <summary>Per-statement budget for creating + migrating the database (#1111).</summary>
private const int MigrationCommandTimeoutSeconds = 300;
/// <summary>Creates and migrates the database.</summary>
public SqlServerTestDatabase() : this(null)
{
}
/// <summary>Creates the database migrated up to <paramref name="targetMigration"/> (latest when null).</summary>
/// <param name="targetMigration">A migration id or name to stop at — e.g. to seed rows a later migration refuses.</param>
public SqlServerTestDatabase(string? targetMigration)
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
// #1114: a migration whose applock was lost to a dropped connection is retried ONCE under a fresh name.
for (var attempt = 1; ; attempt++)
{
_databaseName = $"OtOpcUaConfig_Test_{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
ConnectionString =
$"Server={server};Database={_databaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;" +
$"Connect Timeout={ConnectTimeoutSeconds};";
try
{
CreateAndMigrate(targetMigration);
return;
}
catch (Exception ex) when (attempt == 1 && IsLostMigrationLock(ex))
{
Dispose(); // drop the half-migrated database; the retry mints a new name
}
}
}
private void CreateAndMigrate(string? targetMigration)
{
// #1111: the migration runs with a generous command timeout. Several SQL-backed classes create + migrate their
// own database in parallel on a SHARED server, and under load a single migration statement (observed: the
// migration lock's sp_releaseapplock) overran the provider's 30 s default — failing whichever test happened to
// be constructing its database, with nothing about the behaviour under test involved.
using var ctx = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
.UseSqlServer(ConnectionString, o => o.CommandTimeout(MigrationCommandTimeoutSeconds)).Options);
if (targetMigration is null) ctx.Database.Migrate();
else ctx.GetService<Microsoft.EntityFrameworkCore.Migrations.IMigrator>().Migrate(targetMigration);
}
/// <summary>
/// #1114: whether a migration failed because EF's migration applock (<c>__EFMigrationsLock</c>) was lost — on a
/// heavily loaded server a dropped connection releases the session lock, and the final <c>sp_releaseapplock</c>
/// then fails with "Cannot release the application lock … because it is not currently held" (SQL error 1223).
/// The database is left half-migrated, so the harness retries ONCE under a fresh database name.
/// </summary>
/// <param name="ex">The migration failure.</param>
/// <returns><see langword="true"/> for a lost migration lock.</returns>
internal static bool IsLostMigrationLock(Exception ex)
{
for (var e = ex; e is not null; e = e.InnerException)
{
if (e is SqlException sql && (sql.Number == 1223
|| sql.Message.Contains("not currently held", StringComparison.OrdinalIgnoreCase)))
return true;
if (e.Message.Contains("Cannot release the application lock", StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
/// <summary>A new context on the database.</summary>
/// <returns>The context.</returns>
public OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(ConnectionString).Options);
/// <summary>A factory over <see cref="NewContext"/>.</summary>
/// <returns>The factory.</returns>
public IDbContextFactory<OtOpcUaConfigDbContext> Factory() => new ContextFactory(this);
/// <summary>Drops the database (best effort; a leak is reaped by the Configuration suite).</summary>
public void Dispose()
{
try
{
SqlConnection.ClearAllPools();
var master = new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
using var conn = new SqlConnection(master);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = @"
DECLARE @sql nvarchar(max);
IF DB_ID(@name) IS NOT NULL
BEGIN
SET @sql = N'ALTER DATABASE ' + QUOTENAME(@name) + N' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' +
N'DROP DATABASE ' + QUOTENAME(@name) + N';';
EXEC sp_executesql @sql;
END";
cmd.Parameters.Add(new SqlParameter("@name", _databaseName));
cmd.ExecuteNonQuery();
}
catch (Exception)
{
// Best effort — see the class remarks.
}
}
private sealed class ContextFactory(SqlServerTestDatabase owner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public OtOpcUaConfigDbContext CreateDbContext() => owner.NewContext();
}
}