Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests/QuestDbFixture.cs
T

265 lines
13 KiB
C#

using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using Npgsql;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.Historian.QuestDb.IntegrationTests;
/// <summary>
/// Env-gated QuestDB for the historian integration tests. <c>HISTORIAN_QUESTDB_TEST_CONNECTION</c> absent ⇒
/// <see cref="SkipReason"/> is set, nothing connects and every test calls <c>Assert.Skip</c>. Present ⇒ tests isolate
/// from each other with <see cref="UniquePrefix"/>; every prefix handed out is dropped on dispose (and a test may
/// drop its own early with <see cref="DropPrefixAsync"/>). Never touches a table outside those prefixes.
/// <para>
/// <b>Leak hygiene (#1062).</b> Teardown never lets one failed drop abandon the remaining prefixes (each prefix and each
/// table is dropped independently, with retries — a table QuestDB reports busy is retried), and a killed run (no teardown)
/// is covered by a stale sweep: every handed-out prefix is recorded with its time in the
/// <see cref="RegistryTable"/>, and at fixture start any <c>t&lt;12 hex&gt;_*</c> table whose prefix was registered
/// more than <see cref="StaleAfter"/> ago is dropped. A matching table with no registry row (a leak from before the
/// registry, or a concurrent run of an older build) is <i>adopted</i> — registered now — so it is dropped one
/// <see cref="StaleAfter"/> later, never while a live run could still own it. Only tables whose name matches
/// <see cref="TestTableName"/> are ever touched.
/// </para>
/// </summary>
public sealed class QuestDbFixture : IAsyncLifetime
{
/// <summary>Env var holding an Npgsql connection string for QuestDB's PG-wire port.</summary>
public const string ConnectionEnvVar = "HISTORIAN_QUESTDB_TEST_CONNECTION";
private readonly ConcurrentBag<string> _prefixes = new();
/// <summary>Records every prefix handed out and when (QuestDB has no table-creation time to age tables by).</summary>
public const string RegistryTable = "otopcua_test_prefix_registry";
/// <summary>How old a registered prefix must be before the start-of-fixture sweep drops its tables.</summary>
public static readonly TimeSpan StaleAfter = TimeSpan.FromDays(1);
/// <summary>The only table names the fixture ever drops: a <see cref="UniquePrefix"/> (<c>t</c> + 12 hex + <c>_</c>) then anything.</summary>
public static readonly Regex TestTableName = new("^t[0-9a-f]{12}_", RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>The 14-character <see cref="UniquePrefix"/> a test table name starts with, or null when it is not a test table.</summary>
/// <param name="tableName">A table name.</param>
/// <returns>The prefix, or null.</returns>
public static string? TestPrefixOf(string tableName) => TestTableName.IsMatch(tableName) ? tableName[..14] : null;
/// <summary>Why tests must skip, or null when QuestDB is available.</summary>
public string? SkipReason { get; private set; }
/// <summary>The Npgsql connection string. Valid only when <see cref="SkipReason"/> is null.</summary>
public string ConnectionString { get; private set; } = "";
/// <summary>Skips the calling test when the gate is closed.</summary>
public void SkipIfUnavailable()
{
if (SkipReason is not null) Assert.Skip(SkipReason);
}
/// <summary>A fresh, valid table prefix (<c>"t" + 12 hex + "_"</c>) that nothing uses yet; dropped on dispose.</summary>
/// <returns>The prefix.</returns>
public string UniquePrefix()
{
var p = "t" + Guid.NewGuid().ToString("N")[..12] + "_";
_prefixes.Add(p);
if (SkipReason is null) Register(p); // so a killed run's tables can be aged out by the next start
return p;
}
/// <summary>Options targeting this fixture's QuestDB under <paramref name="prefix"/>.</summary>
/// <param name="prefix">Table prefix (normally from <see cref="UniquePrefix"/>).</param>
/// <param name="retentionDays">Optional TTL.</param>
/// <param name="autoCreate">AutoCreateSchema.</param>
/// <returns>Valid options.</returns>
/// <remarks>
/// Pooled connections idle for more than a second are closed (<c>Connection Idle Lifetime</c> /
/// <c>Connection Pruning Interval</c>). Many tests build their own <see cref="QuestDbConnection"/> (one Npgsql
/// data source each) and never dispose it; with Npgsql's default 300 s idle lifetime their pooled connections
/// piled up until QuestDB's PG-wire limit (64) was reached and later tests' opens timed out after 15 s.
/// </remarks>
public QuestDbHistorianOptions Options(string prefix, int? retentionDays = null, bool autoCreate = true) => new()
{
ConnectionString = new NpgsqlConnectionStringBuilder(ConnectionString)
{
ConnectionIdleLifetime = 1,
ConnectionPruningInterval = 1,
}.ConnectionString,
TablePrefix = prefix,
RetentionDays = retentionDays,
AutoCreateSchema = autoCreate,
VisibilityTimeout = VisibilityTimeout,
};
/// <summary>
/// The read-your-writes wait the tests use. The production default (5 s) is too tight for the SHARED fixture: its docker
/// host is routinely CPU-saturated (load average in the hundreds on 22 cores, 2026-12-03), so QuestDB applies a WAL commit
/// late; <c>WaitAsync</c> then gives up silently (a Warning to a null logger) and the test reads back FEWER rows — the
/// "0 rows even on master" symptom (#993). Not a product defect: the timeout is the designed bound. Override with
/// <c>HISTORIAN_QUESTDB_TEST_VISIBILITY_SECONDS</c>.
/// </summary>
public static TimeSpan VisibilityTimeout { get; } =
int.TryParse(Environment.GetEnvironmentVariable("HISTORIAN_QUESTDB_TEST_VISIBILITY_SECONDS"), out var s) && s >= 0
? TimeSpan.FromSeconds(s)
: TimeSpan.FromSeconds(60);
/// <summary>Drops every table whose name starts with <paramref name="prefix"/> (found through <c>tables()</c>).</summary>
/// <param name="prefix">Table prefix.</param>
/// <returns>A task completing when they are gone.</returns>
/// <exception cref="AggregateException">Some tables could not be dropped after retries (the rest were still dropped).</exception>
public async Task DropPrefixAsync(string prefix)
{
if (SkipReason is not null) return;
if (!QuestDbHistorianOptions.IsValidPrefix(prefix)) throw new ArgumentException("Invalid prefix.", nameof(prefix));
await using var ds = NpgsqlDataSource.Create(ConnectionString);
await using var conn = await ds.OpenConnectionAsync().ConfigureAwait(false);
var names = new List<string>();
await using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT table_name FROM tables() WHERE starts_with(table_name, $1)"; // never LIKE: '_' is a wildcard
cmd.Parameters.Add(new NpgsqlParameter { NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Varchar, Value = prefix });
await using var r = await cmd.ExecuteReaderAsync().ConfigureAwait(false);
while (await r.ReadAsync().ConfigureAwait(false)) names.Add(r.GetString(0));
}
var failures = new List<Exception>();
foreach (var n in names)
{
// Independent per table, with retries: one busy/suspended table must not leave its siblings (or later prefixes) behind.
for (var attempt = 1; ; attempt++)
{
try
{
await using var drop = conn.CreateCommand();
drop.CommandText = $"DROP TABLE IF EXISTS {n}";
await drop.ExecuteNonQueryAsync().ConfigureAwait(false);
break;
}
catch (Exception) when (attempt < 5)
{
await Task.Delay(TimeSpan.FromMilliseconds(250 * attempt)).ConfigureAwait(false);
}
catch (Exception ex)
{
failures.Add(new InvalidOperationException($"Could not drop {n}: {ex.Message}", ex));
break;
}
}
}
if (failures.Count > 0) throw new AggregateException(failures);
}
private void Register(string prefix)
{
try
{
using var ds = NpgsqlDataSource.Create(ConnectionString);
using var conn = ds.OpenConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = $"INSERT INTO {RegistryTable} (ts, prefix) VALUES (now(), $1)";
cmd.Parameters.Add(new NpgsqlParameter { NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Varchar, Value = prefix });
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.Error.WriteLine($"QuestDbFixture: could not register prefix {prefix} for stale sweeping: {ex.Message}");
}
}
/// <summary>
/// Start-of-fixture sweep (#1062): drops the tables of registered prefixes older than <see cref="StaleAfter"/> and
/// adopts (registers now) test-pattern tables nobody registered. Best effort — never fails the fixture.
/// </summary>
private async Task SweepStaleAsync()
{
try
{
await using var ds = NpgsqlDataSource.Create(ConnectionString);
await using var conn = await ds.OpenConnectionAsync().ConfigureAwait(false);
await using (var create = conn.CreateCommand())
{
create.CommandText = $"CREATE TABLE IF NOT EXISTS {RegistryTable} (ts TIMESTAMP, prefix SYMBOL) TIMESTAMP(ts) PARTITION BY DAY WAL";
await create.ExecuteNonQueryAsync().ConfigureAwait(false);
}
var registered = new Dictionary<string, DateTime>(); // prefix -> latest registration
try
{
await using var read = conn.CreateCommand();
read.CommandText = $"SELECT prefix, max(ts) FROM {RegistryTable}";
await using var r = await read.ExecuteReaderAsync().ConfigureAwait(false);
while (await r.ReadAsync().ConfigureAwait(false)) registered[r.GetString(0)] = r.GetDateTime(1);
}
catch (Exception ex) { Console.Error.WriteLine($"QuestDbFixture: registry read failed: {ex.Message}"); }
var tables = new List<string>();
await using (var list = conn.CreateCommand())
{
list.CommandText = "SELECT table_name FROM tables()";
await using var r = await list.ExecuteReaderAsync().ConfigureAwait(false);
while (await r.ReadAsync().ConfigureAwait(false)) tables.Add(r.GetString(0));
}
var cutoff = DateTime.UtcNow - StaleAfter;
var stale = new HashSet<string>();
var adopt = new HashSet<string>();
foreach (var t in tables)
{
if (TestPrefixOf(t) is not { } prefix) continue;
if (registered.TryGetValue(prefix, out var at)) { if (at < cutoff) stale.Add(prefix); }
else adopt.Add(prefix);
}
foreach (var prefix in adopt) Register(prefix);
foreach (var prefix in stale)
{
try { await DropPrefixAsync(prefix).ConfigureAwait(false); }
catch (Exception ex) { Console.Error.WriteLine($"QuestDbFixture: stale sweep of {prefix}: {ex.Message}"); }
}
try
{
await using var trim = conn.CreateCommand(); // keep the registry itself small
trim.CommandText = $"ALTER TABLE {RegistryTable} DROP PARTITION WHERE ts < dateadd('d', -30, now())";
await trim.ExecuteNonQueryAsync().ConfigureAwait(false);
}
catch { /* nothing old enough to drop, or not worth failing for */ }
}
catch (Exception ex)
{
Console.Error.WriteLine($"QuestDbFixture: stale sweep skipped: {ex.Message}");
}
}
/// <inheritdoc/>
public async ValueTask InitializeAsync()
{
var cs = Environment.GetEnvironmentVariable(ConnectionEnvVar);
if (string.IsNullOrWhiteSpace(cs))
{
SkipReason = $"{ConnectionEnvVar} is not set; QuestDB historian integration tests skipped.";
return;
}
ConnectionString = cs;
await SweepStaleAsync().ConfigureAwait(false);
}
/// <inheritdoc/>
public async ValueTask DisposeAsync()
{
if (SkipReason is not null) return;
// Every prefix is attempted: a failure on one (reported, not thrown) never abandons the rest; leftovers are aged
// out by the next start's sweep.
foreach (var p in _prefixes.Distinct())
{
try { await DropPrefixAsync(p).ConfigureAwait(false); }
catch (Exception ex) { Console.Error.WriteLine($"QuestDbFixture: teardown of {p} incomplete: {ex.Message}"); }
}
NpgsqlConnection.ClearAllPools();
}
}
/// <summary>Shares one fixture across the QuestDB integration tests.</summary>
[CollectionDefinition(Name)]
public sealed class QuestDbCollection : ICollectionFixture<QuestDbFixture>
{
/// <summary>Collection name.</summary>
public const string Name = "QuestDb";
}