Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs
T
Joseph Doherty ae9d917b73 test(controlplane): #1111 guard-and-flip reopen test: wait for recovery, prove non-vacuity, capture the interleaving
On_sql_server_a_closure_between_guard_and_flip_is_not_reopened failed once with no message. Interleaving
analysis + repro found no product race (the guard-RowVersion-conditioned flip held in every run, and
removing that conditioning makes the test fail), but three test-side defects:

- Vacuous interleaving: ResolveOne returns once PreStart ran, while the recovery load runs after a
  Task.Yield on the pool. A late load could take the interposer's first countdown slot, so the closure
  fired BEFORE the guard read and the test passed without exercising the race. The test now waits for
  ConfigPublishCoordinatorReadiness == Ready and asserts both counted contexts came from DispatchWrites.
- A throwing closure (shared SQL refusing / timing out) surfaced only as a bare "Fired should be true"
  timeout; it is now captured and reported with its exception.
- No context on failure: every assertion now carries a timeline of context hand-outs (offset, thread,
  countdown, calling coordinator frame), the closure outcome and a dump of both rows.

The reproduced failures were all in SqlServerTestDatabase construction: transport errors / connection
refused while the shared central SQL was stopped, and a migration statement (sp_releaseapplock)
overrunning the 30 s default command timeout while several SQL-backed classes migrate in parallel on a
loaded server. Migration now runs with a 300 s command timeout and a 60 s connect timeout.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-05 00:45:50 -05:00

98 lines
4.9 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 readonly string _databaseName;
/// <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;
_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};";
// #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>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();
}
}