diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs index f8dde3958..ef598f375 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs @@ -466,7 +466,7 @@ public async Task Cancellation_during_blocked_insert_rolls_back_business_changes var commit = transaction.CommitAsync(cancellation.Token); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); // Cancel only after PostgreSQL confirms the insert is waiting on our held lock. - while (await database.Scalar("SELECT count(*) FROM pg_stat_activity WHERE wait_event='advisory'") == 0) + while (await database.Scalar("SELECT count(*) FROM pg_stat_activity WHERE wait_event='advisory' AND datname = current_database()") == 0) await Task.Delay(10, timeout.Token); cancellation.Cancel(); await Assert.That(async () => await commit).Throws(); diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/ChangeCaptureTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/ChangeCaptureTests.cs index 14771966f..34edf1905 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/ChangeCaptureTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/ChangeCaptureTests.cs @@ -47,7 +47,7 @@ public async Task Registration_validates_protocol_limits_and_duplicate_names() public async Task Startup_requires_persistent_slot_and_insert_only_unfiltered_publication() { await using var fixture = new PostgreSqlFixture(); - await fixture.StartAsync(logicalReplication: true); + await fixture.StartAsync(); await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); await PostgreSqlOutboxStoreTests.CreateSchema(source); using var worker = Worker(source, fixture.ConnectionString, new()); @@ -62,7 +62,7 @@ public async Task Startup_requires_persistent_slot_and_insert_only_unfiltered_pu public async Task Captures_commits_drains_pre_slot_backlog_and_preserves_ordered_and_future_rows() { await using var fixture = new PostgreSqlFixture(); - await fixture.StartAsync(logicalReplication: true); + await fixture.StartAsync(); await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); await PostgreSqlOutboxStoreTests.CreateSchema(source); for (var i = 1; i <= 5; i++) await Insert(source, Id(i)); @@ -94,7 +94,7 @@ public async Task Captures_commits_drains_pre_slot_backlog_and_preserves_ordered public async Task Shutdown_after_native_acceptance_replays_same_identity_and_body_on_restart() { await using var fixture = new PostgreSqlFixture(); - await fixture.StartAsync(logicalReplication: true); + await fixture.StartAsync(); await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); await PostgreSqlOutboxStoreTests.CreateSchema(source); await Provision(source, fixture.ConnectionString); @@ -137,7 +137,7 @@ public async Task Shutdown_after_native_acceptance_replays_same_identity_and_bod public async Task Failed_send_stays_durable_after_checkpoint_and_restart_recovers_without_new_insert() { await using var fixture = new PostgreSqlFixture(); - await fixture.StartAsync(logicalReplication: true); + await fixture.StartAsync(); await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); await PostgreSqlOutboxStoreTests.CreateSchema(source); await Provision(source, fixture.ConnectionString); @@ -167,9 +167,12 @@ public async Task Failed_send_stays_durable_after_checkpoint_and_restart_recover finally { await second.StopAsync(timeout.Token); } } + // Replication slot names are unique per server, which every test shares. + private static string Slot => TestContext.Current!.Isolation.GetIsolatedName("orders"); + private static PostgreSqlChangeCaptureOptions Options(int batchSize = 3, bool retainSentMessages = false) => new() { - Slot = new("orders"), Replication = new("orders", PgOutputProtocolVersion.V1), BatchSize = batchSize, RetainSentMessages = retainSentMessages + Slot = new(Slot), Replication = new("orders", PgOutputProtocolVersion.V1), BatchSize = batchSize, RetainSentMessages = retainSentMessages }; [Test] @@ -179,7 +182,7 @@ public async Task Failed_send_stays_durable_after_checkpoint_and_restart_recover public async Task Database_failure_propagates_without_checkpoint_and_restart_recovers(string phase) { await using var fixture = new PostgreSqlFixture(); - await fixture.StartAsync(logicalReplication: true); + await fixture.StartAsync(); await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); await PostgreSqlOutboxStoreTests.CreateSchema(source); await Provision(source, fixture.ConnectionString); @@ -211,7 +214,7 @@ await Sql(source, $""" catch (OperationCanceledException) when (observed.IsCancellationRequested) { } await Assert.That(first.ExecuteTask!.IsFaulted).IsTrue(); await Assert.That(async () => await first.ExecuteTask!).Throws(); - await using var checkpoint = source.CreateCommand("SELECT confirmed_flush_lsn < @position FROM pg_replication_slots WHERE slot_name = 'orders'"); + await using var checkpoint = source.CreateCommand($"SELECT confirmed_flush_lsn < @position FROM pg_replication_slots WHERE slot_name = '{Slot}'"); checkpoint.Parameters.AddWithValue("position", NpgsqlDbType.PgLsn, position); await Assert.That(await checkpoint.ExecuteScalarAsync(timeout.Token) is true).IsTrue(); await Assert.That(await Count(source)).IsEqualTo(1L); @@ -235,7 +238,7 @@ await Sql(source, $""" public async Task Non_transient_replication_failure_stops_host() { await using var fixture = new PostgreSqlFixture(); - await fixture.StartAsync(logicalReplication: true); + await fixture.StartAsync(); await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); await PostgreSqlOutboxStoreTests.CreateSchema(source); await Provision(source, fixture.ConnectionString); @@ -261,14 +264,14 @@ public async Task Non_transient_replication_failure_stops_host() public async Task Transient_native_disconnect_reconnects_to_persistent_slot_and_captures_new_commits() { await using var fixture = new PostgreSqlFixture(); - await fixture.StartAsync(logicalReplication: true); + await fixture.StartAsync(); await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); await PostgreSqlOutboxStoreTests.CreateSchema(source); await Provision(source, fixture.ConnectionString); var transport = new RecordingTransport(); using var worker = new PostgreSqlChangeCaptureWorker(source, () => new(fixture.ConnectionString) { WalReceiverStatusInterval = TimeSpan.FromMilliseconds(25) }, - new() { Slot = new("orders"), Replication = new("orders", PgOutputProtocolVersion.V1), ReconnectDelay = TimeSpan.FromMilliseconds(20) }, + new() { Slot = new(Slot), Replication = new("orders", PgOutputProtocolVersion.V1), ReconnectDelay = TimeSpan.FromMilliseconds(20) }, [transport], NullLogger.Instance, NullLogger.Instance, NullLogger.Instance); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); @@ -277,7 +280,7 @@ public async Task Transient_native_disconnect_reconnects_to_persistent_slot_and_ { await Streaming(source, timeout.Token); int previous; - await using (var command = source.CreateCommand("SELECT active_pid FROM pg_replication_slots WHERE slot_name = 'orders'")) + await using (var command = source.CreateCommand($"SELECT active_pid FROM pg_replication_slots WHERE slot_name = '{Slot}'")) previous = (int)(await command.ExecuteScalarAsync(timeout.Token))!; await using (var kill = source.CreateCommand("SELECT pg_terminate_backend(@pid)")) { @@ -287,7 +290,7 @@ public async Task Transient_native_disconnect_reconnects_to_persistent_slot_and_ var position = await Insert(source, Id(1)); await Acknowledged(source, position, timeout.Token); await Assert.That(transport.Ids.SequenceEqual([Id(1)])).IsTrue(); - await using var current = source.CreateCommand("SELECT active_pid FROM pg_replication_slots WHERE slot_name = 'orders'"); + await using var current = source.CreateCommand($"SELECT active_pid FROM pg_replication_slots WHERE slot_name = '{Slot}'"); await Assert.That((int)(await current.ExecuteScalarAsync(timeout.Token))!).IsNotEqualTo(previous); } finally { await worker.StopAsync(timeout.Token); } @@ -303,7 +306,7 @@ private static async Task Provision(NpgsqlDataSource source, string connectionSt await Sql(source, $"CREATE PUBLICATION orders FOR TABLE relayer_outbox WITH (publish = '{publish}')"); await using var connection = new LogicalReplicationConnection(connectionString); await connection.Open(); - await connection.CreatePgOutputReplicationSlot("orders"); + await connection.CreatePgOutputReplicationSlot(Slot); } private static async Task Insert(NpgsqlDataSource source, Guid id, @@ -326,13 +329,13 @@ private static async Task Insert(NpgsqlDataSource sourc private static Task Streaming(NpgsqlDataSource source, CancellationToken token) => Until(async () => { - await using var command = source.CreateCommand("SELECT EXISTS (SELECT 1 FROM pg_replication_slots s JOIN pg_stat_replication r ON r.pid = s.active_pid WHERE s.slot_name = 'orders' AND r.state = 'streaming')"); + await using var command = source.CreateCommand($"SELECT EXISTS (SELECT 1 FROM pg_replication_slots s JOIN pg_stat_replication r ON r.pid = s.active_pid WHERE s.slot_name = '{Slot}' AND r.state = 'streaming')"); return (bool)(await command.ExecuteScalarAsync(token))!; }, token); private static Task Acknowledged(NpgsqlDataSource source, NpgsqlLogSequenceNumber position, CancellationToken token) => Until(async () => { - await using var command = source.CreateCommand("SELECT confirmed_flush_lsn >= @position FROM pg_replication_slots WHERE slot_name = 'orders'"); + await using var command = source.CreateCommand($"SELECT confirmed_flush_lsn >= @position FROM pg_replication_slots WHERE slot_name = '{Slot}'"); command.Parameters.AddWithValue("position", NpgsqlDbType.PgLsn, position); return await command.ExecuteScalarAsync(token) is true; }, token); diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs index 9c3e4d478..00ad47599 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/InboxTests.cs @@ -642,7 +642,7 @@ internal async Task WaitForInboxLock() await connection.OpenAsync(timeout.Token); while (true) { - await using var command = new NpgsqlCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query LIKE 'INSERT INTO %test_inbox%'", connection); + await using var command = new NpgsqlCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query LIKE 'INSERT INTO %test_inbox%' AND datname = current_database()", connection); if ((long)(await command.ExecuteScalarAsync(timeout.Token))! > 0) return; await Task.Delay(10, timeout.Token); } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/MaintenanceTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/MaintenanceTests.cs index c58a50af8..0cb17f8e7 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/MaintenanceTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/MaintenanceTests.cs @@ -69,7 +69,7 @@ public async Task Connected_sweeper_holds_leadership_through_native_send_then_ri await using var observer = NpgsqlDataSource.Create(fixture.ConnectionString); while (true) { - await using var waiting = observer.CreateCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query LIKE 'INSERT INTO %leases%'"); + await using var waiting = observer.CreateCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query LIKE 'INSERT INTO %leases%' AND datname = current_database()"); if ((long)(await waiting.ExecuteScalarAsync(timeout.Token))! > 0) break; await Task.Yield(); } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs index 2d568971a..786cf38f9 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs @@ -225,7 +225,7 @@ public async Task Database_connection_crash_replays_head_before_later_rows_durin await entered.Task.WaitAsync(cancellation.Token); try { - await using var terminate = source.CreateCommand("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle in transaction' AND query LIKE 'UPDATE %SET claim_token%'"); + await using var terminate = source.CreateCommand("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle in transaction' AND query LIKE 'UPDATE %SET claim_token%' AND datname = current_database()"); await terminate.ExecuteNonQueryAsync(cancellation.Token); } finally { release.TrySetResult(); } @@ -633,7 +633,7 @@ private static async Task WaitForLock(NpgsqlDataSource source, CancellationToken { while (true) { - await using var command = source.CreateCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query LIKE 'INSERT INTO %leases%'"); + await using var command = source.CreateCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' AND query LIKE 'INSERT INTO %leases%' AND datname = current_database()"); if ((long)(await command.ExecuteScalarAsync(cancellationToken))! > 0) return; await Task.Yield(); } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/Parallelism.cs b/tests/Relayer.Outbox.PostgreSql.Tests/Parallelism.cs deleted file mode 100644 index ed68c550b..000000000 --- a/tests/Relayer.Outbox.PostgreSql.Tests/Parallelism.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Relayer.Outbox.PostgreSql.Tests; -using TUnit.Core.Interfaces; - -// Each database test starts its own PostgreSQL container. Bound their combined -// startup and connection load, including across different test classes. -[assembly: ParallelLimiter] - -namespace Relayer.Outbox.PostgreSql.Tests; - -public sealed class PostgreSqlTestParallelLimit : IParallelLimit -{ - public int Limit => 4; -} diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlConnectionTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlConnectionTests.cs index aef79f7d0..97e3f49c7 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlConnectionTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlConnectionTests.cs @@ -39,7 +39,6 @@ public async Task Fixture_uses_plaintext_password_authentication_without_encrypt await Assert.That(settings.SslMode).IsEqualTo(SslMode.Disable); await Assert.That(settings.GssEncryptionMode).IsEqualTo(GssEncryptionMode.Disable); await Assert.That(settings.Pooling).IsFalse(); - await Assert.That(settings.Timeout).IsEqualTo(2); } [Test] diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixture.cs b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixture.cs index e04646fad..af639c74e 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixture.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixture.cs @@ -1,82 +1,97 @@ -using System.Diagnostics; using Npgsql; namespace Relayer.Outbox.PostgreSql.Tests; +// One database per fixture on the session's shared server, so tests run in parallel +// without seeing each other's tables, sessions or replication slots. internal sealed class PostgreSqlFixture : IAsyncDisposable { - private readonly string _name = "relayer-schema-test-" + Guid.NewGuid().ToString("N"); - private readonly Func> _docker; - private readonly Action _reportCleanupFailure; - private bool _startupAttempted; + private NpgsqlDataSource? _admin; + public string Database { get; } = TestContext.Current!.Isolation.GetIsolatedName(Guid.NewGuid().ToString("N")[..8]); public string ConnectionString { get; private set; } = ""; - public PostgreSqlFixture() : this(new DockerCommand().RunAsync, ReportCleanupFailure) { } - - internal PostgreSqlFixture(Func> docker, Action reportCleanupFailure) + public async Task StartAsync() { - _docker = docker; - _reportCleanupFailure = reportCleanupFailure; + var session = await PostgreSqlSession.Current; + _admin = session.Admin; + await Execute($"CREATE DATABASE {Database}"); + ConnectionString = session.Server.ConnectionString.Replace("Database=postgres", "Database=" + Database); } - public async Task StartAsync(bool logicalReplication = false) + public async ValueTask DisposeAsync() { - // The daemon can create the container even if the CLI never returns its ID. - _startupAttempted = true; + if (_admin is null) return; try { - await _docker(["run", "--detach", "--rm", "--name", _name, "--publish", "127.0.0.1::5432", - "--env", "POSTGRES_PASSWORD=relayer-test", "postgres:18-alpine", - .. logicalReplication ? new[] { "-c", "wal_level=logical" } : []]); - var port = (await _docker(["port", _name, "5432/tcp"])).Trim().Split(':')[^1]; - // This container has neither TLS nor Kerberos. Native encryption fallback can - // reconnect after authentication fails and replace the original failure. - ConnectionString = $"Host=127.0.0.1;Port={port};Username=postgres;Password=relayer-test;Database=postgres;Pooling=false;Timeout=2;SSL Mode=Disable;GSS Encryption Mode=Disable"; - var timeout = Stopwatch.StartNew(); - while (true) + // Includes databases a test created with this one's name as their prefix. + var databases = new List(); + await using (var command = _admin.CreateCommand("SELECT datname FROM pg_database WHERE starts_with(datname, $1)")) { - try - { - await using var connection = new NpgsqlConnection(ConnectionString); - await connection.OpenAsync(); - return; - } - catch (NpgsqlException) when (timeout.Elapsed < TimeSpan.FromSeconds(60)) - { - await Task.Delay(200); - } + command.Parameters.AddWithValue(Database); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) databases.Add(reader.GetString(0)); } + foreach (var database in databases) await Execute($"DROP DATABASE {database} WITH (FORCE)"); } catch (Exception exception) { - exception.Data["DockerContainerName"] = _name; - Console.Error.WriteLine($"PostgreSQL fixture startup failed. After Docker recovers, clean up with: docker rm --force --volumes {_name}"); - throw; + // Throwing here would replace an exception unwinding through await using. + var failure = new InvalidOperationException($"Could not drop PostgreSQL test database {Database}.", exception); + Console.Error.WriteLine(failure); + TestContext.Current!.StateBag.GetOrAdd("PostgreSqlFixture.CleanupFailures", static _ => new List()).Add(failure); } } - public async ValueTask DisposeAsync() + private async Task Execute(string sql) { - if (!_startupAttempted) return; - _startupAttempted = false; + await using var command = _admin!.CreateCommand(sql); + await command.ExecuteNonQueryAsync(); + } +} + +public static class PostgreSqlSession +{ + // Started by the first test that needs a database, so filtered runs of pure unit tests start no container. + private static Lazy> _shared = new(StartAsync); + + internal static Task Current => Volatile.Read(ref _shared).Value; + + // Admin is pooled, unlike the tests' own connections: creating and dropping databases should not add connection churn. + internal sealed record Session(PostgreSqlServer Server, NpgsqlDataSource Admin, List CleanupFailures); + + private static async Task StartAsync() + { + var failures = new List(); + var server = new PostgreSqlServer(new DockerCommand().RunAsync, failure => + { + Console.Error.WriteLine(failure); + failures.Add(failure); + }); try { - await _docker(["rm", "--force", "--volumes", _name]); + await server.StartAsync(); + return new(server, NpgsqlDataSource.Create(server.ConnectionString.Replace("Pooling=false", "Pooling=true")), failures); } - catch (Exception exception) + catch { - var failure = new InvalidOperationException( - $"PostgreSQL fixture cleanup failed. After Docker recovers, run: docker rm --force --volumes {_name}", exception); - // Throwing here would replace an exception unwinding through await using. - _reportCleanupFailure(failure); + await server.DisposeAsync(); + throw; } } - private static void ReportCleanupFailure(Exception failure) + [After(TestSession)] + public static async Task StopAsync() { - Console.Error.WriteLine(failure); - var context = TestContext.Current ?? throw new InvalidOperationException("Fixture cleanup requires a TUnit test context.", failure); - var failures = context.StateBag.GetOrAdd("PostgreSqlFixture.CleanupFailures", static _ => new List()); - failures.Add(failure); + // Like TUnit's own per-session instances, a later session in this process starts afresh. + var shared = Interlocked.Exchange(ref _shared, new(StartAsync)); + if (!shared.IsValueCreated) return; + // Wait for a startup still in flight (every test may have given up on it) so its container is not left behind. + Session session; + try { session = await shared.Value; } + // A failed startup already removed its container and failed the tests that needed it. + catch { return; } + await session.Admin.DisposeAsync(); + await session.Server.DisposeAsync(); + if (session.CleanupFailures.Count > 0) throw new AggregateException("PostgreSQL server cleanup failed.", session.CleanupFailures); } } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixtureTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixtureTests.cs index 6510c6904..498ebef59 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixtureTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlFixtureTests.cs @@ -38,7 +38,7 @@ public async Task Failed_startup_retains_ownership_and_cleanup_does_not_replace_ var cleanup = new TimeoutException("docker rm timed out"); var calls = new List(); var failures = new List(); - var fixture = new PostgreSqlFixture(args => + var fixture = new PostgreSqlServer(args => { calls.Add(args); if (args[0] == "rm") return Task.FromException(cleanup); @@ -66,7 +66,7 @@ public async Task Cleanup_failure_does_not_replace_an_exception_from_the_test_bo { var primary = new InvalidOperationException("test body failed"); var failures = new List(); - var fixture = new PostgreSqlFixture(args => args[0] == "rm" + var fixture = new PostgreSqlServer(args => args[0] == "rm" ? Task.FromException(new TimeoutException("docker rm timed out")) : Task.FromException(new TimeoutException("docker run timed out")), failures.Add); // A failed run may still have created the named container. @@ -79,17 +79,33 @@ public async Task Cleanup_failure_does_not_replace_an_exception_from_the_test_bo await Assert.That(failures.Count).IsEqualTo(1); } + [Test] + public async Task Dispose_drops_the_database_and_those_created_under_its_name() + { + var fixture = new PostgreSqlFixture(); + await fixture.StartAsync(); + var admin = (await PostgreSqlSession.Current).Admin; + await using (var create = admin.CreateCommand($"CREATE DATABASE {fixture.Database}_tenant")) await create.ExecuteNonQueryAsync(); + await using var count = admin.CreateCommand("SELECT count(*) FROM pg_database WHERE starts_with(datname, $1)"); + count.Parameters.AddWithValue(fixture.Database); + await Assert.That((long)(await count.ExecuteScalarAsync())!).IsEqualTo(2L); + + await fixture.DisposeAsync(); + + await Assert.That((long)(await count.ExecuteScalarAsync())!).IsEqualTo(0L); + } + [Test] public async Task Disposing_an_unused_fixture_does_not_invoke_Docker() { - await using var fixture = new PostgreSqlFixture(_ => throw new InvalidOperationException("Unexpected Docker invocation"), _ => { }); + await using var fixture = new PostgreSqlServer(_ => throw new InvalidOperationException("Unexpected Docker invocation"), _ => { }); } [Test] public async Task Successful_cleanup_removes_only_the_owned_container() { var calls = new List(); - var fixture = new PostgreSqlFixture(args => + var fixture = new PostgreSqlServer(args => { calls.Add(args); return args[0] == "run" ? Task.FromException(new TimeoutException("startup")) : Task.FromResult(""); diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlServer.cs b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlServer.cs new file mode 100644 index 000000000..44b436d86 --- /dev/null +++ b/tests/Relayer.Outbox.PostgreSql.Tests/PostgreSqlServer.cs @@ -0,0 +1,78 @@ +using System.Diagnostics; +using Npgsql; + +namespace Relayer.Outbox.PostgreSql.Tests; + +// The session's PostgreSQL container. Tests reach it through PostgreSqlFixture, which gives each its own database. +internal sealed class PostgreSqlServer : IAsyncDisposable +{ + private readonly string _name = "relayer-schema-test-" + Guid.NewGuid().ToString("N"); + private readonly Func> _docker; + private readonly Action _reportCleanupFailure; + private bool _startupAttempted; + public string ConnectionString { get; private set; } = ""; + + internal PostgreSqlServer(Func> docker, Action reportCleanupFailure) + { + _docker = docker; + _reportCleanupFailure = reportCleanupFailure; + } + + public async Task StartAsync() + { + // The daemon can create the container even if the CLI never returns its ID. + _startupAttempted = true; + try + { + await _docker(["run", "--detach", "--rm", "--name", _name, "--publish", "127.0.0.1::5432", + "--env", "POSTGRES_PASSWORD=relayer-test", "postgres:18-alpine", + // Every test shares this server: allow logical replication and their combined sessions. + "-c", "wal_level=logical", "-c", "max_connections=1000", + "-c", "max_replication_slots=100", "-c", "max_wal_senders=100", + // Dropping a database forces a checkpoint. The data is disposable, so do not sync it to disk. + "-c", "fsync=off"]); + var port = (await _docker(["port", _name, "5432/tcp"])).Trim().Split(':')[^1]; + // This container has neither TLS nor Kerberos. Native encryption fallback can + // reconnect after authentication fails and replace the original failure. + ConnectionString = $"Host=127.0.0.1;Port={port};Username=postgres;Password=relayer-test;Database=postgres;Pooling=false;SSL Mode=Disable;GSS Encryption Mode=Disable"; + var timeout = Stopwatch.StartNew(); + while (true) + { + try + { + // A short timeout keeps this probe retrying; tests keep the default so a busy shared server is not a failure. + await using var connection = new NpgsqlConnection(ConnectionString + ";Timeout=2"); + await connection.OpenAsync(); + return; + } + catch (NpgsqlException) when (timeout.Elapsed < TimeSpan.FromSeconds(60)) + { + await Task.Delay(200); + } + } + } + catch (Exception exception) + { + exception.Data["DockerContainerName"] = _name; + Console.Error.WriteLine($"PostgreSQL fixture startup failed. After Docker recovers, clean up with: docker rm --force --volumes {_name}"); + throw; + } + } + + public async ValueTask DisposeAsync() + { + if (!_startupAttempted) return; + _startupAttempted = false; + try + { + await _docker(["rm", "--force", "--volumes", _name]); + } + catch (Exception exception) + { + var failure = new InvalidOperationException( + $"PostgreSQL fixture cleanup failed. After Docker recovers, run: docker rm --force --volumes {_name}", exception); + // Throwing here would replace an exception unwinding through await using. + _reportCleanupFailure(failure); + } + } +} diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/TenantDispatchTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/TenantDispatchTests.cs index 4514ebec5..6eeb0f51d 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/TenantDispatchTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/TenantDispatchTests.cs @@ -213,7 +213,7 @@ public async Task Contended_native_lease_does_not_duplicate_or_cross_tenant_disp { while (true) { - await using var observer = fixture.Entries[0].DataSource.CreateCommand("SELECT count(*) FROM pg_stat_activity WHERE wait_event_type='Lock' AND query LIKE 'INSERT INTO %leases%'"); + await using var observer = fixture.Entries[0].DataSource.CreateCommand($"SELECT count(*) FROM pg_stat_activity WHERE wait_event_type='Lock' AND query LIKE 'INSERT INTO %leases%' AND application_name='{fixture.Application}'"); if ((long)(await observer.ExecuteScalarAsync(timeout.Token))! > 0) break; await Task.Yield(); } @@ -258,7 +258,8 @@ public async Task Turn_deadline_releases_admission_for_an_unrelated_tenant() public async Task Ordered_lanes_progress_after_lane_or_tenant_deadline(bool tenantDeadline) { await using var fixture = new Stores(); - await fixture.Start(1, lanes: 3, leaseDuration: TimeSpan.FromSeconds(4)); + // Wall-clock deadlines: the lane deadline is half the lease. Leave room for a busy shared server. + await fixture.Start(1, lanes: 3, leaseDuration: TimeSpan.FromSeconds(12)); var store = fixture.Entries[0]; for (var lane = 0; lane < 3; lane++) await Insert(store, lane + 1, lane); var transport = new Transport(async (message, token) => @@ -266,7 +267,7 @@ public async Task Ordered_lanes_progress_after_lane_or_tenant_deadline(bool tena if (MessageId(message) == Id(1)) await Task.Delay(Timeout.Infinite, token); }); using var worker = new PostgreSqlTenantDispatcher(fixture.Catalog, - new() { TurnTimeout = TimeSpan.FromSeconds(tenantDeadline ? 1 : 5), RecoveryDelay = TimeSpan.Zero }, + new() { TurnTimeout = TimeSpan.FromSeconds(tenantDeadline ? 3 : 15), RecoveryDelay = TimeSpan.Zero }, [transport], NullLoggerFactory.Instance); await worker.PassAsync(default); if (tenantDeadline) await worker.PassAsync(default); @@ -358,7 +359,7 @@ public async Task Exhausted_direct_turn_resumes_recovery_ordered_dispatch_and_cl if (MessageId(message) == Id(1)) await Task.Delay(Timeout.Infinite, token); }); using var worker = new PostgreSqlTenantDispatcher(fixture.Catalog, - new() { TurnTimeout = TimeSpan.FromSeconds(1), RecoveryDelay = TimeSpan.Zero, InboxRetention = TimeSpan.FromHours(1), BatchSize = 1 }, + new() { TurnTimeout = TimeSpan.FromSeconds(3), RecoveryDelay = TimeSpan.Zero, InboxRetention = TimeSpan.FromHours(1), BatchSize = 1 }, [transport], NullLoggerFactory.Instance); worker.GetDispatcher(store.TenantId).Committed(queued, 1); // Keep the direct queue busy on every turn, including after canceled durable claims. @@ -477,6 +478,8 @@ private sealed class Catalog : ITenantSource private sealed class Stores : IAsyncDisposable { private readonly PostgreSqlFixture _fixture = new(); + // The server is shared: count only this test's sessions. + internal string Application { get; } = "tenant-dispatch-" + Guid.NewGuid().ToString("N"); internal Catalog Catalog { get; } = new(); internal PostgreSqlTenantStore[] Entries { get; private set; } = []; internal async Task Start(int count, bool databases = false, int lanes = 1, TimeSpan? leaseDuration = null) @@ -485,13 +488,13 @@ internal async Task Start(int count, bool databases = false, int lanes = 1, Time Entries = new PostgreSqlTenantStore[count]; for (var i = 0; i < count; i++) { - var settings = new NpgsqlConnectionStringBuilder(_fixture.ConnectionString) { ApplicationName = "tenant-dispatch-test" }; + var settings = new NpgsqlConnectionStringBuilder(_fixture.ConnectionString) { ApplicationName = Application }; if (databases) { await using var admin = NpgsqlDataSource.Create(_fixture.ConnectionString); - await using var create = admin.CreateCommand($"CREATE DATABASE tenant_{i}"); + await using var create = admin.CreateCommand($"CREATE DATABASE {_fixture.Database}_tenant_{i}"); await create.ExecuteNonQueryAsync(); - settings.Database = $"tenant_{i}"; + settings.Database = $"{_fixture.Database}_tenant_{i}"; } var source = NpgsqlDataSource.Create(settings.ConnectionString); var options = new PostgreSqlOutboxOptions { Schema = $"tenant_{i}", Lanes = lanes, LeaseDuration = leaseDuration ?? TimeSpan.FromSeconds(30) }; @@ -504,7 +507,7 @@ internal async Task Start(int count, bool databases = false, int lanes = 1, Time internal async Task Connections() { await using var observer = NpgsqlDataSource.Create(_fixture.ConnectionString); - await using var command = observer.CreateCommand("SELECT count(*) FROM pg_stat_activity WHERE application_name='tenant-dispatch-test'"); + await using var command = observer.CreateCommand($"SELECT count(*) FROM pg_stat_activity WHERE application_name='{Application}'"); return (long)(await command.ExecuteScalarAsync())!; } internal async Task WaitForNoConnections(CancellationToken cancellationToken = default) @@ -516,7 +519,7 @@ internal async Task WaitForNoConnections(CancellationToken cancellationToken = d await using var observer = new NpgsqlConnection(_fixture.ConnectionString); await observer.OpenAsync(timeout.Token); await using var command = new NpgsqlCommand( - "SELECT count(*) FROM pg_stat_activity WHERE application_name='tenant-dispatch-test'", observer); + $"SELECT count(*) FROM pg_stat_activity WHERE application_name='{Application}'", observer); while ((long)(await command.ExecuteScalarAsync(timeout.Token))! != 0) await Task.Delay(10, timeout.Token); } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/TenantStoreSelectionTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/TenantStoreSelectionTests.cs index 3660fc136..8eb5e3b6b 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/TenantStoreSelectionTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/TenantStoreSelectionTests.cs @@ -482,9 +482,9 @@ internal async Task Start(bool separateDatabases) var settings = new NpgsqlConnectionStringBuilder(_fixture.ConnectionString) { SearchPath = schema }; if (separateDatabases) { - await using var create = new NpgsqlCommand($"CREATE DATABASE {id}", admin); + await using var create = new NpgsqlCommand($"CREATE DATABASE {_fixture.Database}_{id}", admin); await create.ExecuteNonQueryAsync(); - settings.Database = id; + settings.Database = $"{_fixture.Database}_{id}"; } var store = new TenantStore(id, NpgsqlDataSource.Create(settings.ConnectionString), schema); _stores.Add(store); diff --git a/website/docs/contributing/testing.md b/website/docs/contributing/testing.md index b460f48d2..8068ba9e6 100644 --- a/website/docs/contributing/testing.md +++ b/website/docs/contributing/testing.md @@ -29,3 +29,20 @@ Docker's memory. When you add a broker test, use the shared instance and name everything the test creates uniquely, for example with `TestContext.Current!.Isolation`. Do not add `[ParallelLimiter]` or `[NotInParallel]` to make a test pass. + +## PostgreSQL outbox suite + +`tests/Relayer.Outbox.PostgreSql.Tests` starts one PostgreSQL container per test run, +on the first test that needs it. `PostgreSqlFixture` creates a database on that server +for each test and drops it afterwards, so the suite runs at full parallelism without a +limiter. A test that queries server-wide views such as `pg_stat_activity` or +`pg_replication_slots` must scope the query to its own database, application name or +replication slot; name server-wide objects with `TestContext.Current!.Isolation`. + +The suite opens a new connection for most commands. On macOS, Docker Desktop forwards +about 8,000 new connections per 30 seconds across the whole machine before it starts +closing them, and one run of this suite uses about a third of that. Repeating the +whole suite several times back to back can therefore fail with +`Exception while reading from stream` on every test. Run the tests that cover your +change instead, or wait 30 seconds between full runs. Linux hosts and CI are not +affected.