diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java index 77366f9f..e7a7f940 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.adapter.outbound.support.messaging.JsonIntegrationEventEncoder; import dev.caskeleton.application.idempotency.RequestFingerprint; @@ -97,8 +98,8 @@ class DurableOperationSubmissionOutboxIntegrationTest { } @BeforeEach - void empty() throws SQLException { - execute("TRUNCATE durable_operation, outbox_event"); + void empty() { + BoundedTruncate.truncate(support.dataSource(), "durable_operation", "outbox_event"); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java index 11b16b5c..f15405d8 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.idempotency.RequestFingerprint; import dev.caskeleton.application.operation.DurableOperationClaim; @@ -17,12 +18,10 @@ import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.Connection; -import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.Duration; import java.time.Instant; -import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; @@ -76,18 +75,6 @@ class JpaDurableOperationStoreContractTest extends DurableOperationStoreContract /** Longer than worker-b may queue and inside the transaction timeout, so worker-a commits. */ private static final Duration WORKER_A_HOLDS_AT_MOST = WORKER_B_QUEUES_AT_MOST.multipliedBy(2); - /** - * How long the cleanup's TRUNCATE may wait for a lock on the table before it fails. - * - *

Twice the 1 s {@code deadlock_timeout} after which PostgreSQL cancels an autovacuum that - * blocks the TRUNCATE, and a commit still in flight ends in milliseconds: a lock held longer is a - * transaction a test left open, which an unbounded TRUNCATE would wait for for good. - */ - private static final String CLEANUP_LOCK_TIMEOUT = "2s"; - - /** PostgreSQL's SQLSTATE for a lock wait that ran out its {@code lock_timeout}. */ - private static final String LOCK_NOT_AVAILABLE = "55P03"; - private static JpaPlatformContractSupport support; private static AnnotationConfigApplicationContext context; @@ -112,86 +99,10 @@ class JpaDurableOperationStoreContractTest extends DurableOperationStoreContract } } - /** - * Empties the table, or fails naming the session whose lock on it stopped the TRUNCATE. - * - *

{@code SET LOCAL} ends with this transaction: the connection goes back to the pool the - * adapter under test borrows from, and the adapter must not inherit the cleanup's bound. The pool - * restores autocommit when the connection goes back. - */ + /** Empties the table, or fails naming the session whose lock on it stopped the TRUNCATE. */ @BeforeEach - void empty() throws SQLException { - try (Connection connection = support.connection(); - Statement statement = connection.createStatement()) { - connection.setAutoCommit(false); - try { - statement.execute("SET LOCAL lock_timeout = '" + CLEANUP_LOCK_TIMEOUT + "'"); - statement.execute("TRUNCATE durable_operation"); - connection.commit(); - } catch (SQLException failure) { - // A broken connection fails the rollback too; that must not replace the original failure. - try { - connection.rollback(); - } catch (SQLException rollbackFailure) { - failure.addSuppressed(rollbackFailure); - throw failure; - } - if (!LOCK_NOT_AVAILABLE.equals(failure.getSQLState())) { - throw failure; - } - String holders; - try { - holders = lockHolders(statement); - } catch (SQLException lookFailure) { - failure.addSuppressed(lookFailure); - holders = "unknown, the lookup failed (suppressed below)"; - } - throw new IllegalStateException( - "the cleanup's TRUNCATE durable_operation gave up after waiting " - + CLEANUP_LOCK_TIMEOUT - + " for a lock on the table. Sessions locking it: " - + holders, - failure); - } - } - } - - /** Every other session's lock on the table, held or queued, and what it last ran. */ - private static String lockHolders(Statement statement) throws SQLException { - List holders = new ArrayList<>(); - try (ResultSet rows = - statement.executeQuery( - """ - SELECT l.pid, l.mode, l.granted, a.state, - extract(epoch FROM now() - a.xact_start)::int AS open_seconds, - left(a.query, 160) AS last_statement - FROM pg_locks l - JOIN pg_stat_activity a ON a.pid = l.pid - WHERE l.locktype = 'relation' - AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database()) - AND l.relation = 'durable_operation'::regclass - AND l.pid <> pg_backend_pid() - ORDER BY l.pid, l.mode - """)) { - while (rows.next()) { - String lock = - "pid " - + rows.getInt("pid") - + " " - + rows.getString("mode") - + (rows.getBoolean("granted") ? " held" : " queued") - + ", " - + rows.getString("state"); - int openSeconds = rows.getInt("open_seconds"); - // No transaction start: the holder ended between reading pg_locks and pg_stat_activity. - String open = - rows.wasNull() ? ", no transaction open any more" : " for " + openSeconds + " s"; - holders.add(lock + open + ", last statement: " + rows.getString("last_statement")); - } - } - return holders.isEmpty() - ? "none any more; the holder ended between the timeout and this look" - : String.join("; ", holders); + void empty() { + BoundedTruncate.truncate(support.dataSource(), "durable_operation"); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/BoundedTruncateContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/BoundedTruncateContractTest.java new file mode 100644 index 00000000..77b60602 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/platform/BoundedTruncateContractTest.java @@ -0,0 +1,262 @@ +package dev.caskeleton.adapter.outbound.persistence.platform; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.SingleConnectionDataSource; + +/** + * The cleanup TRUNCATE the integration tests share, against a database of its own. + * + *

A test that locks a table on purpose becomes the leftover holder it is about when it fails + * halfway, which is why #66 kept no permanent test of its cleanup. Two things stop that here: the + * tables live in this class's own database, and every holder ends itself through {@code + * idle_in_transaction_session_timeout}. The second also ends the test when the bound is gone: the + * test thread would otherwise wait in the TRUNCATE for the holder it closes only afterwards. + */ +@Tag("jpa-contract") +class BoundedTruncateContractTest { + + /** Far past the TRUNCATE's 2 s wait, and short enough that a broken bound fails the test soon. */ + private static final String HOLDER_ENDS_ITSELF_AFTER = "10s"; + + private static JpaPlatformContractSupport support; + + @BeforeAll + static void start() throws SQLException { + support = JpaPlatformContractSupport.start(); + execute("CREATE TABLE truncate_parent (id int PRIMARY KEY)"); + execute( + "CREATE TABLE truncate_child" + + " (id int PRIMARY KEY, parent_id int NOT NULL REFERENCES truncate_parent (id))"); + execute("CREATE TABLE truncate_other (id int PRIMARY KEY)"); + } + + @AfterAll + static void stop() { + if (support != null) { + support.close(); + } + } + + @BeforeEach + void oneRowEach() throws SQLException { + execute("DELETE FROM truncate_child"); + execute("DELETE FROM truncate_parent"); + execute("DELETE FROM truncate_other"); + execute("INSERT INTO truncate_parent (id) VALUES (1)"); + execute("INSERT INTO truncate_child (id, parent_id) VALUES (1, 1)"); + execute("INSERT INTO truncate_other (id) VALUES (1)"); + } + + @Test + void truncateEmptiesTheNamedTablesAndNoOther() throws SQLException { + // when + BoundedTruncate.truncate(support.dataSource(), "truncate_child", "truncate_parent"); + + // then + assertThat(List.of(rows("truncate_child"), rows("truncate_parent"), rows("truncate_other"))) + .containsExactly(0, 0, 1); + } + + @Test + void truncateCascadeAlsoEmptiesATableThatReferencesANamedOne() throws SQLException { + // when + BoundedTruncate.truncateCascade(support.dataSource(), "truncate_parent"); + + // then + assertThat(List.of(rows("truncate_child"), rows("truncate_parent"), rows("truncate_other"))) + .containsExactly(0, 0, 1); + } + + @Test + void aLockLeftOnANamedTableFailsTheTruncateNamingItsHolder() throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_other")) { + // given + int holderPid = pidOf(holder); + + // when + Throwable thrown = + catchThrowable(() -> BoundedTruncate.truncate(support.dataSource(), "truncate_other")); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("gave up after waiting 2000 ms for a lock") + .hasMessageContaining( + "pid " + holderPid + " AccessShareLock held on public.truncate_other") + .cause() + .isInstanceOfSatisfying( + SQLException.class, cause -> assertThat(cause.getSQLState()).isEqualTo("55P03")); + } + } + + @Test + void aLockOnAReferencingTableTheCascadeWasNotGivenIsNamedToo() throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_child")) { + // given + int holderPid = pidOf(holder); + + // when + Throwable thrown = + catchThrowable( + () -> BoundedTruncate.truncateCascade(support.dataSource(), "truncate_parent")); + + // then + assertThat(thrown) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "pid " + holderPid + " AccessShareLock held on public.truncate_child"); + } + } + + @Test + void aConnectionComesBackWithAutocommitOnAndNoLockTimeoutAfterEmptying() throws SQLException { + try (Connection physical = ownConnection()) { + // when + BoundedTruncate.truncate(new SingleConnectionDataSource(physical, true), "truncate_other"); + + // then + assertThat(List.of(physical.getAutoCommit(), lockTimeoutOf(physical))) + .containsExactly(true, "0"); + } + } + + @Test + void aConnectionComesBackWithAutocommitOnAndNoLockTimeoutAfterGivingUp() throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_other"); + Connection physical = ownConnection()) { + // when + Throwable thrown = + catchThrowable( + () -> + BoundedTruncate.truncate( + new SingleConnectionDataSource(physical, true), "truncate_other")); + + // then + // A TRUNCATE that did not give up leaves no exception: compare that as null, not as an NPE. + assertThat( + Arrays.asList( + thrown == null ? null : thrown.getClass(), + physical.getAutoCommit(), + lockTimeoutOf(physical))) + .containsExactly(IllegalStateException.class, true, "0"); + } + } + + @Test + void aConnectionLentWithoutAutocommitComesBackWithNoTransactionOpenAfterGivingUp() + throws SQLException { + try (Connection holder = holdingAccessShareOn("truncate_other"); + Connection physical = ownConnection()) { + // given + int physicalPid = pidOf(physical); + physical.setAutoCommit(false); + + // when + Throwable thrown = + catchThrowable( + () -> + BoundedTruncate.truncate( + new SingleConnectionDataSource(physical, true), "truncate_other")); + + // then + assertThat( + Arrays.asList( + thrown == null ? null : thrown.getClass(), + physical.getAutoCommit(), + sessionStateOf(physicalPid))) + .containsExactly(IllegalStateException.class, false, "idle"); + } + } + + /** + * A connection outside every pool, so nothing resets it on return. + * + *

Hikari puts autocommit back itself when a connection goes back; a data source that does not + * is the one the class must still leave as it found it. + */ + private static Connection ownConnection() throws SQLException { + return DriverManager.getConnection(support.jdbcUrl(), support.username(), support.password()); + } + + /** A session left in a transaction that read the table, as a test that never committed. */ + private static Connection holdingAccessShareOn(String table) throws SQLException { + Connection holder = ownConnection(); + try (Statement statement = holder.createStatement()) { + statement.execute( + "SET idle_in_transaction_session_timeout = '" + HOLDER_ENDS_ITSELF_AFTER + "'"); + holder.setAutoCommit(false); + statement.execute("SELECT count(*) FROM " + table); + } catch (SQLException failure) { + holder.close(); + throw failure; + } + return holder; + } + + private static int pidOf(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT pg_backend_pid()")) { + row.next(); + return row.getInt(1); + } + } + + private static String lockTimeoutOf(Connection connection) throws SQLException { + try (Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SHOW lock_timeout")) { + row.next(); + return row.getString(1); + } + } + + /** + * What the server shows a session doing between statements, as another session sees it. + * + *

{@code idle in transaction} when a transaction is still open, {@code idle} when none is. + * Asked from outside because the driver, with autocommit off, begins a transaction on the session + * with the first statement it sends. + */ + private static String sessionStateOf(int pid) throws SQLException { + try (Connection connection = support.connection(); + PreparedStatement statement = + connection.prepareStatement("SELECT state FROM pg_stat_activity WHERE pid = ?")) { + statement.setInt(1, pid); + try (ResultSet row = statement.executeQuery()) { + row.next(); + return row.getString(1); + } + } + } + + private static int rows(String table) throws SQLException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement(); + ResultSet row = statement.executeQuery("SELECT count(*) FROM " + table)) { + row.next(); + return row.getInt(1); + } + } + + private static void execute(String sql) throws SQLException { + try (Connection connection = support.connection(); + Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } +} diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java index 068f1dc0..b3a28872 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/FileserverPostgreSqlStack.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaFileMetadata; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.StorageNamespace; import dev.caskeleton.application.fileserver.api.metadata.FileOwner; @@ -128,9 +129,14 @@ final class FileserverPostgreSqlStack implements AutoCloseable { /** Deletes every Fileserver row, children first. */ void empty() { - jdbc.execute( - "TRUNCATE fs_recovery_item, fs_cleanup_item, fs_quota_reservation," - + " fs_verification_result, fs_upload_session, fs_file CASCADE"); + BoundedTruncate.truncateCascade( + postgres.dataSource(), + "fs_recovery_item", + "fs_cleanup_item", + "fs_quota_reservation", + "fs_verification_result", + "fs_upload_session", + "fs_file"); } @Override diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java index eb67ee3a..4307724d 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlFileserverReclamationIntegrationTest.java @@ -11,6 +11,7 @@ import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaQuotaReclaim; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaRecoveryQueue; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaStagingUploadLocator; import dev.caskeleton.adapter.outbound.persistence.fileserver.JpaUploadSession; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.fileserver.api.ContentKey; import dev.caskeleton.application.fileserver.api.FileId; import dev.caskeleton.application.fileserver.api.FileState; @@ -135,9 +136,14 @@ class PostgreSqlFileserverReclamationIntegrationTest extends CleanupQueuePortCon @BeforeEach void truncate() { enqueueBy = Instant.now().plusSeconds(5); - jdbc.execute( - "TRUNCATE fs_recovery_item, fs_cleanup_item, fs_quota_reservation," - + " fs_verification_result, fs_upload_session, fs_file CASCADE"); + BoundedTruncate.truncateCascade( + postgres.dataSource(), + "fs_recovery_item", + "fs_cleanup_item", + "fs_quota_reservation", + "fs_verification_result", + "fs_upload_session", + "fs_file"); } @Test diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java index 02818b8d..c3617d73 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlNotificationBackgroundPassIntegrationTest.java @@ -13,6 +13,7 @@ import dev.caskeleton.adapter.outbound.persistence.notification.platform.reposit import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.NotificationRequestJpaRepository; import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.ProviderEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.notification.platform.repository.RecipientDeliveryJpaRepository; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransaction; import dev.caskeleton.application.notification.platform.api.CollapseScope; import dev.caskeleton.application.notification.platform.api.CollapseSpec; @@ -134,10 +135,13 @@ class PostgreSqlNotificationBackgroundPassIntegrationTest { @BeforeEach void assemble() { jdbc = new JdbcTemplate(database.dataSource()); - jdbc.execute( - "TRUNCATE notification_provider_event, notification_delivery_attempt," - + " notification_recipient_delivery, notification_contact_point, notification_request" - + " CASCADE"); + BoundedTruncate.truncateCascade( + database.dataSource(), + "notification_provider_event", + "notification_delivery_attempt", + "notification_recipient_delivery", + "notification_contact_point", + "notification_request"); transactions = new SpringTransaction(context.getBean(PlatformTransactionManager.class)); RecipientDeliveryJpaRepository recipients = context.getBean(RecipientDeliveryJpaRepository.class); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java index f2bf2152..94c08f64 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.catchThrowable; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxLease; import dev.caskeleton.application.transaction.TransactionPort; @@ -72,7 +73,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest { @BeforeEach void openContext() { jdbc = new JdbcTemplate(dataSource); - jdbc.execute("TRUNCATE outbox_event"); + BoundedTruncate.truncate(dataSource, "outbox_event"); context = OutboxIntegrationSupport.buildContext( dataSource, event -> {}, Clock.fixed(NOW, ZoneOffset.UTC)); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java index 54f253ca..44871d71 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxConcurrentRelayIntegrationTest.java @@ -3,6 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness; import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.JpaOutboxStore; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.outbox.OutboxAppendPort; import dev.caskeleton.application.outbox.OutboxEventStatus; import dev.caskeleton.application.outbox.OutboxRelayResult; @@ -59,7 +60,7 @@ class PostgreSqlOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingC @BeforeEach void emptyOutbox() { - new JdbcTemplate(sharedDataSource).execute("TRUNCATE outbox_event"); + BoundedTruncate.truncate(sharedDataSource, "outbox_event"); } @AfterAll diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java index 2e30f995..7ea8c92a 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionContractTest.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.persistence.transaction; import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.application.transaction.TransactionPort; import dev.caskeleton.application.transaction.testkit.TransactionPortContract; import dev.caskeleton.application.transaction.testkit.TransactionProbe; @@ -69,7 +70,7 @@ class SpringTransactionContractTest extends TransactionPortContract { @BeforeEach void empty() { - jdbc.execute("truncate transaction_contract_probe"); + BoundedTruncate.truncate(support.dataSource(), "transaction_contract_probe"); } @Override diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/BoundedTruncate.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/BoundedTruncate.java new file mode 100644 index 00000000..51827948 --- /dev/null +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/postgresql/BoundedTruncate.java @@ -0,0 +1,204 @@ +package dev.caskeleton.adapter.outbound.persistence.testkit.postgresql; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.regex.Pattern; +import javax.sql.DataSource; + +/** + * Empties tables between integration tests without waiting for good on a lock somebody left. + * + *

A plain {@code TRUNCATE} on a pooled connection runs with the server's {@code lock_timeout}, + * which is 0: no bound. When an earlier test leaves a transaction open on one of the tables, the + * next test's cleanup waits for it until the lane's own timeout ends the run, and the report names + * the cleanup rather than the transaction that stopped it. This runs the {@code TRUNCATE} in one + * transaction after {@code SET LOCAL lock_timeout}, and when the wait runs out it fails with every + * session that holds or awaits a lock on a table of this database. + * + *

{@code SET LOCAL} ends with the transaction: the connection goes back to the pool the code + * under test borrows from, and that code must not inherit the cleanup's bound. Autocommit is put + * back by this class rather than left to the pool, so a data source that does not reset it on + * return gets the connection back as it lent it. + */ +public final class BoundedTruncate { + + /** + * How long the {@code TRUNCATE} may wait for its lock before it fails. + * + *

Twice the 1 s {@code deadlock_timeout} after which PostgreSQL cancels an autovacuum that + * blocks the {@code TRUNCATE}, and a commit still in flight ends in milliseconds: a lock held + * longer is a transaction a test left open. + */ + public static final Duration LOCK_TIMEOUT = Duration.ofSeconds(2); + + /** PostgreSQL's SQLSTATE for a lock wait that ran out its {@code lock_timeout}. */ + private static final String LOCK_NOT_AVAILABLE = "55P03"; + + /** An unquoted table name, optionally schema-qualified: nothing else reaches the statement. */ + private static final Pattern TABLE_NAME = + Pattern.compile("[a-z_][a-z0-9_]*(\\.[a-z_][a-z0-9_]*)?"); + + private BoundedTruncate() {} + + /** + * Empties the named tables, or fails naming the sessions whose locks stopped it. + * + * @throws IllegalStateException when the lock wait ran out, or the {@code TRUNCATE} failed + */ + public static void truncate(DataSource dataSource, String... tables) { + empty(dataSource, "TRUNCATE " + tableList(tables)); + } + + /** + * Empties the named tables and every table that references them. + * + *

{@code CASCADE} also locks the referencing tables it was not given, which is why a failure + * lists the locks on every table of the database, not only the named ones. + * + * @throws IllegalStateException when the lock wait ran out, or the {@code TRUNCATE} failed + */ + public static void truncateCascade(DataSource dataSource, String... tables) { + empty(dataSource, "TRUNCATE " + tableList(tables) + " CASCADE"); + } + + private static String tableList(String... tables) { + Objects.requireNonNull(tables, "tables"); + if (tables.length == 0) { + throw new IllegalArgumentException("name at least one table to truncate"); + } + for (String table : tables) { + if (table == null || !TABLE_NAME.matcher(table).matches()) { + throw new IllegalArgumentException("not an unquoted table name: " + table); + } + } + return String.join(", ", tables); + } + + private static void empty(DataSource dataSource, String truncate) { + Objects.requireNonNull(dataSource, "dataSource"); + try (Connection connection = dataSource.getConnection()) { + boolean autoCommit = connection.getAutoCommit(); + connection.setAutoCommit(false); + Throwable failure = null; + try { + inOneTransaction(connection, truncate); + } catch (Throwable thrown) { + failure = thrown; + throw thrown; + } finally { + restoreAutoCommit(connection, autoCommit, failure); + } + } catch (SQLException failure) { + throw new IllegalStateException("the cleanup's " + truncate + " failed", failure); + } + } + + private static void inOneTransaction(Connection connection, String truncate) throws SQLException { + try (Statement statement = connection.createStatement()) { + try { + statement.execute("SET LOCAL lock_timeout = '" + LOCK_TIMEOUT.toMillis() + "ms'"); + statement.execute(truncate); + connection.commit(); + } catch (SQLException failure) { + // A broken connection fails the rollback too; that must not replace the original failure. + try { + connection.rollback(); + } catch (SQLException rollbackFailure) { + failure.addSuppressed(rollbackFailure); + throw failure; + } + if (!LOCK_NOT_AVAILABLE.equals(failure.getSQLState())) { + throw failure; + } + String holders; + try { + holders = lockHolders(statement); + } catch (SQLException lookFailure) { + failure.addSuppressed(lookFailure); + holders = "unknown, the lookup failed (suppressed below)"; + } + // The lookup opened a transaction of its own; end it here rather than leave it to + // autocommit going back on, which does not happen when the connection was lent without it. + try { + connection.rollback(); + } catch (SQLException endFailure) { + failure.addSuppressed(endFailure); + } + throw new IllegalStateException( + "the cleanup's " + + truncate + + " gave up after waiting " + + LOCK_TIMEOUT.toMillis() + + " ms for a lock. Other sessions locking tables of this database: " + + holders, + failure); + } + } + } + + /** Puts autocommit back; a failure to do so rides on the original failure when there is one. */ + private static void restoreAutoCommit( + Connection connection, boolean autoCommit, Throwable failure) throws SQLException { + try { + connection.setAutoCommit(autoCommit); + } catch (SQLException restoreFailure) { + if (failure == null) { + throw restoreFailure; + } + failure.addSuppressed(restoreFailure); + } + } + + /** Every other session's lock on a table of this database, held or queued, and what it ran. */ + private static String lockHolders(Statement statement) throws SQLException { + List holders = new ArrayList<>(); + try (ResultSet rows = + statement.executeQuery( + """ + SELECT l.pid, n.nspname || '.' || c.relname AS locked_table, l.mode, l.granted, + a.state, + extract(epoch FROM now() - a.xact_start)::int AS open_seconds, + left(a.query, 160) AS last_statement + FROM pg_locks l + JOIN pg_class c ON c.oid = l.relation + JOIN pg_namespace n ON n.oid = c.relnamespace + JOIN pg_stat_activity a ON a.pid = l.pid + WHERE l.locktype = 'relation' + AND l.database = (SELECT oid FROM pg_database WHERE datname = current_database()) + AND c.relkind IN ('r', 'p') + AND n.nspname <> 'information_schema' + AND n.nspname NOT LIKE 'pg\\_%' + AND l.pid <> pg_backend_pid() + ORDER BY l.pid, locked_table, l.mode + """)) { + while (rows.next()) { + String lock = + "pid " + + rows.getInt("pid") + + " " + + rows.getString("mode") + + (rows.getBoolean("granted") ? " held" : " queued") + + " on " + + rows.getString("locked_table") + + ", " + + rows.getString("state"); + int openSeconds = rows.getInt("open_seconds"); + // No transaction start: the holder's transaction ended between reading pg_locks and + // pg_stat_activity while its session stayed connected. A session that disconnected in + // between has no pg_stat_activity row, so the join drops it. + String open = + rows.wasNull() ? ", no transaction open any more" : " for " + openSeconds + " s"; + holders.add(lock + open + ", last statement: " + rows.getString("last_statement")); + } + } + return holders.isEmpty() + ? "none any more; the holder ended between the timeout and this look" + : String.join("; ", holders); + } +} diff --git a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java b/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java index 962d5b73..ea2f4adb 100644 --- a/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java +++ b/src/bootstrap/app/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java @@ -8,10 +8,12 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder import com.jayway.jsonpath.JsonPath; import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; +import dev.caskeleton.adapter.outbound.persistence.testkit.postgresql.BoundedTruncate; import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer; import dev.caskeleton.composition.runtime.context.DomainContextConfig; import java.util.List; import java.util.Set; +import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -74,6 +76,8 @@ class DurableOperationCompositionIntegrationTest { @Autowired private JdbcTemplate jdbc; + @Autowired private DataSource dataSource; + @DynamicPropertySource static void runtimeProperties(DynamicPropertyRegistry registry) { Flyway.configure() @@ -89,7 +93,7 @@ class DurableOperationCompositionIntegrationTest { @BeforeEach void empty() { SecurityContextHolder.clearContext(); - jdbc.execute("TRUNCATE durable_operation, outbox_event"); + BoundedTruncate.truncate(dataSource, "durable_operation", "outbox_event"); } @Test