feat: jpa, messaging, notification, mongo, graphql 어댑터터 구현체 추가

This commit is contained in:
DongHyeonka
2026-08-15 13:01:58 +09:00
parent e23ed9486e
commit f56dd3e4eb
174 changed files with 10338 additions and 1274 deletions
@@ -0,0 +1,77 @@
package dev.caskeleton.messaging.inbox;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.reliability.InboxRepository;
import java.time.Instant;
import java.util.Objects;
import java.util.function.Supplier;
/**
* Runs a handler's side effect at most once per message and consumer.
*
* <p>The reservation and the side effect must share one transaction. This class does not open that
* transaction itself — the caller supplies a runner that does — because the boundary belongs to the
* application's data access layer, and a nested or separate transaction here would silently break
* the guarantee while still looking correct.
*
* <p>A duplicate is not an error. It is the expected consequence of at-least-once delivery, so the
* skip path is a normal outcome rather than an exception.
*/
public final class IdempotentConsumer {
private final InboxRepository inbox;
private final TransactionRunner transactions;
/**
* Creates an idempotent consumer.
*
* @param inbox the inbox storage
* @param transactions runs work inside one database transaction
*/
public IdempotentConsumer(InboxRepository inbox, TransactionRunner transactions) {
this.inbox = Objects.requireNonNull(inbox, "inbox must not be null");
this.transactions = Objects.requireNonNull(transactions, "transactions must not be null");
}
/**
* Runs the side effect unless this message was already processed.
*
* @param <T> the side effect's result type
* @param messageId the logical message identity
* @param consumerId the consumer's stable identity
* @param now the current instant
* @param sideEffect the business work
* @return the outcome, including whether the work ran
*/
public <T> InboxOutcome<T> runOnce(
MessageId messageId, String consumerId, Instant now, Supplier<T> sideEffect) {
Objects.requireNonNull(messageId, "messageId must not be null");
Objects.requireNonNull(sideEffect, "sideEffect must not be null");
Objects.requireNonNull(now, "now must not be null");
if (consumerId == null || consumerId.isBlank()) {
throw new IllegalArgumentException("consumerId must not be blank");
}
return transactions.inTransaction(
() -> {
if (!inbox.reserve(messageId, consumerId, now)) {
return InboxOutcome.duplicate();
}
return InboxOutcome.processed(sideEffect.get());
});
}
/** Runs work inside exactly one database transaction. */
@FunctionalInterface
public interface TransactionRunner {
/**
* Runs the supplied work in a transaction and returns its result.
*
* @param <T> the result type
* @param work the work to run
* @return the work's result
*/
<T> T inTransaction(Supplier<T> work);
}
}
@@ -0,0 +1,65 @@
package dev.caskeleton.messaging.inbox;
import dev.caskeleton.messaging.reliability.InboxRepository;
import java.time.Instant;
import java.util.Objects;
/**
* Deletes inbox rows that are older than the retention policy allows.
*
* <p>Deletes in bounded batches. A single unbounded {@code DELETE} over a table that has been
* accumulating for weeks holds locks long enough to block the very reservations the inbox exists to
* serve, so the cleanup would cause the outage it is meant to prevent.
*
* <p>The policy is validated before the first deletion. Running a cleanup under a retention that is
* shorter than the redelivery window would actively create the duplicate-processing bug, so the job
* refuses to start rather than dutifully deleting the rows.
*/
public final class InboxCleanupJob {
/** How many rows one pass deletes before yielding. */
public static final int DEFAULT_BATCH_SIZE = 1_000;
private final InboxRepository inbox;
private final InboxRetentionPolicy policy;
private final int maxBatches;
/**
* Creates a cleanup job.
*
* @param inbox the inbox storage
* @param policy the retention policy
* @param maxBatches how many batches one run may delete
*/
public InboxCleanupJob(InboxRepository inbox, InboxRetentionPolicy policy, int maxBatches) {
this.inbox = Objects.requireNonNull(inbox, "inbox must not be null");
this.policy = Objects.requireNonNull(policy, "policy must not be null");
if (maxBatches < 1) {
throw new IllegalArgumentException("maxBatches must be at least 1");
}
this.maxBatches = maxBatches;
policy.validate();
}
/**
* Deletes expired rows, up to the configured batch ceiling.
*
* @param now the current instant
* @return how many rows were removed
*/
public int runOnce(Instant now) {
Objects.requireNonNull(now, "now must not be null");
Instant cutoff = policy.cutoff(now);
int removed = 0;
for (int batch = 0; batch < maxBatches; batch++) {
int deleted = inbox.purgeProcessedBefore(cutoff);
removed += deleted;
// A short batch means the backlog is drained; continuing would just re-scan an empty range.
if (deleted == 0) {
break;
}
}
return removed;
}
}
@@ -0,0 +1,34 @@
package dev.caskeleton.messaging.inbox;
import java.util.Optional;
/**
* Whether a message's side effect ran or was suppressed as a duplicate.
*
* @param <T> the side effect's result type
* @param processed true when the side effect ran for the first time
* @param result the side effect's result, absent for a duplicate
*/
public record InboxOutcome<T>(boolean processed, Optional<T> result) {
/**
* Returns an outcome for a first-time delivery.
*
* @param <T> the result type
* @param value the side effect's result
* @return the processed outcome
*/
public static <T> InboxOutcome<T> processed(T value) {
return new InboxOutcome<>(true, Optional.ofNullable(value));
}
/**
* Returns an outcome for a suppressed duplicate.
*
* @param <T> the result type
* @return the duplicate outcome
*/
public static <T> InboxOutcome<T> duplicate() {
return new InboxOutcome<>(false, Optional.empty());
}
}
@@ -0,0 +1,78 @@
package dev.caskeleton.messaging.inbox;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import java.time.Duration;
import java.time.Instant;
import java.util.Objects;
/**
* How long inbox rows are kept, and the rule that makes the number safe.
*
* <p>Retention must exceed the broker's maximum redelivery window. That is not a tuning preference:
* a row pruned while the broker can still redeliver its message turns the inbox into a no-op for
* exactly that message, and the side effect runs a second time. The failure is silent, rare, and
* only happens under the conditions that already made the day bad.
*
* <p>The safety margin is multiplicative rather than additive so that it scales with the window
* itself. A stream whose redelivery window is measured in days needs more slack than one measured
* in minutes, for the same reason: the estimate of that window is proportionally less certain.
*
* @param retention how long a processed row is kept
* @param maximumRedeliveryWindow the longest the broker may redelivery a message
*/
public record InboxRetentionPolicy(Duration retention, Duration maximumRedeliveryWindow) {
/** How much longer than the redelivery window retention must be. */
public static final double REQUIRED_SAFETY_FACTOR = 2.0;
/** The default for a broker whose redelivery window is bounded by a one-day log retention. */
public static final Duration DEFAULT_RETENTION = Duration.ofDays(7);
public InboxRetentionPolicy {
Objects.requireNonNull(retention, "retention must not be null");
Objects.requireNonNull(maximumRedeliveryWindow, "maximumRedeliveryWindow must not be null");
if (retention.isNegative() || retention.isZero()) {
throw new IllegalArgumentException("retention must be positive");
}
if (maximumRedeliveryWindow.isNegative() || maximumRedeliveryWindow.isZero()) {
throw new IllegalArgumentException("maximumRedeliveryWindow must be positive");
}
}
/**
* Refuses a retention that could prune a row the broker can still redeliver.
*
* @throws MessagingConfigurationException when retention is too short
*/
public void validate() {
Duration required = required();
if (retention.compareTo(required) < 0) {
throw new MessagingConfigurationException(
"INBOX_RETENTION_TOO_SHORT",
"inbox retention of %s is below the %s required for a %s redelivery window; a pruned row"
.formatted(retention, required, maximumRedeliveryWindow)
+ " lets a late redelivery apply its effect twice");
}
}
/**
* Returns the shortest retention this redelivery window allows.
*
* @return the minimum safe retention
*/
public Duration required() {
return Duration.ofMillis(
Math.round(maximumRedeliveryWindow.toMillis() * REQUIRED_SAFETY_FACTOR));
}
/**
* Returns the cutoff before which rows may be deleted.
*
* @param now the current instant
* @return the retention cutoff
*/
public Instant cutoff(Instant now) {
Objects.requireNonNull(now, "now must not be null");
return now.minus(retention);
}
}
@@ -0,0 +1,184 @@
package dev.caskeleton.messaging.inbox;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import dev.caskeleton.messaging.reliability.InboxRepository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Objects;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* The PostgreSQL inbox.
*
* <p>Reservation is an {@code INSERT ... ON CONFLICT DO NOTHING} whose affected-row count is the
* answer: one means first delivery, zero means already processed. The composite primary key does
* the work, so there is no read-then-write race — two concurrent deliveries of the same message
* cannot both see "not processed" and both proceed.
*
* <p>The connection-taking overload is the one that matters. Reserving on a connection other than
* the one carrying the business write means the two commit independently, which reopens exactly the
* duplicate window the Inbox exists to close. The no-argument overload is provided only for
* retention sweeps and read-only queries.
*/
public final class JdbcInboxRepository implements InboxRepository {
private static final String RESERVE =
"""
INSERT INTO messaging_inbox (message_id, consumer_id, processed_at)
VALUES (?, ?, ?)
ON CONFLICT (message_id, consumer_id) DO NOTHING
""";
private final DataSource dataSource;
/**
* Creates a repository over a data source.
*
* @param dataSource the inbox data source
*/
public JdbcInboxRepository(DataSource dataSource) {
this.dataSource = Objects.requireNonNull(dataSource, "dataSource must not be null");
}
/**
* Reserves a message on the caller's transactional connection.
*
* <p>Package-private. It used to be public and was the only path that actually joined the
* caller's transaction, while the interface method — the one {@code IdempotentConsumer} calls —
* opened a raw connection that auto-commits. A reservation that commits on its own while the
* business side effect rolls back is a message that will never be redelivered and whose work
* never happened.
*
* @param connection the connection the business write is running on
* @param messageId the logical message identity
* @param consumerId the consumer's stable identity
* @param now the current instant
* @return true when this is the first time
*/
boolean reserve(Connection connection, MessageId messageId, String consumerId, Instant now) {
Objects.requireNonNull(connection, "connection must not be null");
Objects.requireNonNull(messageId, "messageId must not be null");
Objects.requireNonNull(now, "now must not be null");
if (consumerId == null || consumerId.isBlank()) {
throw new IllegalArgumentException("consumerId must not be blank");
}
try (PreparedStatement statement = connection.prepareStatement(RESERVE)) {
statement.setObject(1, messageId.value());
statement.setString(2, consumerId);
statement.setTimestamp(3, Timestamp.from(now));
return statement.executeUpdate() == 1;
} catch (SQLException exception) {
throw new MessagingConfigurationException(
"INBOX_RESERVE_FAILED", "could not reserve an inbox record", exception);
}
}
@Override
public boolean reserve(MessageId messageId, String consumerId, Instant now) {
requireActiveTransaction("reserving an inbox message");
Connection connection = DataSourceUtils.getConnection(dataSource);
try {
return reserve(connection, messageId, consumerId, now);
} finally {
DataSourceUtils.releaseConnection(connection, dataSource);
}
}
/**
* Refuses when there is no transaction to join, or when it cannot write.
*
* <p>The reservation and the side effect it guards have to commit or roll back together. Running
* the reservation on its own connection breaks that on the rollback path only — which is the path
* nobody exercises before production, and the one where the message is lost for good.
*/
private void requireActiveTransaction(String what) {
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new MessagingConfigurationException(
"INBOX_TRANSACTION_REQUIRED",
what
+ " requires an active transaction; a reservation that commits alone marks a message"
+ " processed whose work may still roll back");
}
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new MessagingConfigurationException(
"INBOX_TRANSACTION_REQUIRED",
what + " requires a writable transaction; the current one is read-only");
}
if (!TransactionSynchronizationManager.hasResource(dataSource)) {
throw new MessagingConfigurationException(
"INBOX_TRANSACTION_REQUIRED",
what
+ " requires the active transaction to be bound to this DataSource; it is bound to"
+ " another, so the reservation and the side effect would commit independently");
}
}
@Override
public boolean isProcessed(MessageId messageId, String consumerId) {
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(
"SELECT 1 FROM messaging_inbox WHERE message_id = ? AND consumer_id = ?")) {
statement.setObject(1, messageId.value());
statement.setString(2, consumerId);
try (ResultSet results = statement.executeQuery()) {
return results.next();
}
} catch (SQLException exception) {
throw new MessagingConfigurationException(
"INBOX_QUERY_FAILED", "could not query the inbox", exception);
}
}
@Override
public int purgeProcessedBefore(Instant processedBefore, int limit) {
Objects.requireNonNull(processedBefore, "processedBefore must not be null");
if (limit < 1) {
throw new IllegalArgumentException("a bounded purge deletes at least one row per call");
}
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(
"""
WITH expired AS (
SELECT message_id, consumer_id
FROM messaging_inbox
WHERE processed_at < ?
ORDER BY processed_at
LIMIT ?
FOR UPDATE SKIP LOCKED
)
DELETE FROM messaging_inbox i
USING expired e
WHERE i.message_id = e.message_id AND i.consumer_id = e.consumer_id
""")) {
statement.setTimestamp(1, Timestamp.from(processedBefore));
statement.setInt(2, limit);
return statement.executeUpdate();
} catch (SQLException exception) {
throw new MessagingConfigurationException(
"INBOX_PURGE_FAILED", "a bounded inbox purge failed", exception);
}
}
@Override
public int purgeProcessedBefore(Instant processedBefore) {
Objects.requireNonNull(processedBefore, "processedBefore must not be null");
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement("DELETE FROM messaging_inbox WHERE processed_at < ?")) {
statement.setTimestamp(1, Timestamp.from(processedBefore));
return statement.executeUpdate();
} catch (SQLException exception) {
throw new MessagingConfigurationException(
"INBOX_PURGE_FAILED", "could not purge the inbox", exception);
}
}
}
@@ -0,0 +1,104 @@
package dev.caskeleton.messaging.inbox;
import dev.caskeleton.messaging.api.delivery.HandleResult;
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
import dev.caskeleton.messaging.api.error.FailureCategory;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import dev.caskeleton.messaging.reliability.IdempotentMessageHandler;
import dev.caskeleton.messaging.reliability.InboxResult;
import dev.caskeleton.messaging.reliability.TransactionalMessageAction;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
/**
* The JDBC-backed {@link IdempotentMessageHandler}.
*
* <p>Reservation and effect commit together, in the runner's single transaction. Everything else
* about this class follows from that: it cannot settle the message (settlement is not
* transactional), it cannot publish (the publish would survive a rollback), and it cannot catch and
* swallow the action's exception (the rollback is how the reservation is undone).
*
* <p>An already-reserved message returns success. Under at-least-once delivery a duplicate is the
* normal case, not an error; reporting failure would send a message whose work is complete to the
* dead-letter queue.
*
* @param <T> the payload type
*/
public final class TransactionalInboxHandler<T> implements IdempotentMessageHandler<T> {
private final IdempotentConsumer consumer;
private final Supplier<Instant> clock;
/**
* Creates a handler.
*
* @param consumer the reservation-and-effect runner
* @param clock supplies the current instant
*/
public TransactionalInboxHandler(IdempotentConsumer consumer, Supplier<Instant> clock) {
this.consumer = Objects.requireNonNull(consumer, "consumer must not be null");
this.clock = Objects.requireNonNull(clock, "clock must not be null");
}
@Override
public CompletionStage<HandleResult> handleOnce(
String consumerName, MessageDelivery<T> delivery, TransactionalMessageAction<T> action) {
Objects.requireNonNull(delivery, "delivery must not be null");
Objects.requireNonNull(action, "action must not be null");
if (consumerName == null || consumerName.isBlank()) {
throw new IllegalArgumentException("consumerName must not be blank");
}
try {
InboxOutcome<InboxResult> outcome =
consumer.runOnce(
delivery.message().messageId(),
consumerName,
clock.get(),
() -> {
try {
action.apply(delivery);
} catch (Exception failure) {
// Wrapped, not swallowed: the transaction runner has to see a throw to roll the
// reservation back along with the effect.
throw new ActionFailed(failure);
}
return InboxResult.APPLIED;
});
return CompletableFuture.completedFuture(
outcome.processed() ? HandleResult.success() : duplicateIsSuccess());
} catch (ActionFailed failure) {
return CompletableFuture.completedFuture(retryable(failure.getCause()));
}
}
private static HandleResult duplicateIsSuccess() {
// The effect already ran in an earlier delivery. Settling is correct; redelivering is not.
return HandleResult.success();
}
private static HandleResult retryable(Throwable cause) {
return new HandleResult.Retry(
new FailureDescriptor(
FailureCategory.TRANSIENT_INFRASTRUCTURE,
"INBOX_ACTION_FAILED",
true,
"the transactional action failed and its reservation was rolled back",
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())));
}
/** Carries the action's checked exception out through the transaction runner. */
private static final class ActionFailed extends RuntimeException {
private static final long serialVersionUID = 1L;
private ActionFailed(Throwable cause) {
super(cause);
}
}
}
@@ -0,0 +1,18 @@
-- Consumer inbox.
--
-- The composite primary key is the deduplication mechanism: reserving a message is an INSERT that
-- either succeeds or violates the key, inside the same transaction as the handler's side effect.
-- Two independent consumers of the same event each get their own row, so one cannot suppress the
-- other.
CREATE TABLE messaging_inbox
(
message_id UUID NOT NULL,
consumer_id VARCHAR(160) NOT NULL,
processed_at TIMESTAMPTZ NOT NULL,
CONSTRAINT pk_messaging_inbox PRIMARY KEY (message_id, consumer_id)
);
-- Retention sweeps read this. The window must outlive the broker's maximum redelivery delay:
-- pruning a row before its message can still be redelivered reopens the duplicate this table
-- exists to close.
CREATE INDEX ix_messaging_inbox_processed_at ON messaging_inbox (processed_at);
@@ -0,0 +1,145 @@
package dev.caskeleton.messaging.inbox;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.reliability.InboxRepository;
import java.time.Instant;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
class IdempotentConsumerTest {
private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z");
private final InMemoryInbox inbox = new InMemoryInbox();
private final SingleTransactionRunner transactions = new SingleTransactionRunner();
private final IdempotentConsumer consumer = new IdempotentConsumer(inbox, transactions);
@Test
void theFirstDeliveryRunsTheSideEffect() {
AtomicInteger effects = new AtomicInteger();
MessageId messageId = MessageId.newId();
InboxOutcome<Integer> outcome =
consumer.runOnce(messageId, "order-projection", NOW, effects::incrementAndGet);
assertThat(outcome.processed()).isTrue();
assertThat(outcome.result()).hasValue(1);
assertThat(effects.get()).isEqualTo(1);
}
@Test
void aRedeliverySkipsTheSideEffect() {
AtomicInteger effects = new AtomicInteger();
MessageId messageId = MessageId.newId();
consumer.runOnce(messageId, "order-projection", NOW, effects::incrementAndGet);
InboxOutcome<Integer> second =
consumer.runOnce(messageId, "order-projection", NOW, effects::incrementAndGet);
assertThat(second.processed()).isFalse();
assertThat(second.result()).isEmpty();
assertThat(effects.get()).isEqualTo(1);
}
@Test
void twoConsumersEachProcessTheSameMessageOnce() {
AtomicInteger effects = new AtomicInteger();
MessageId messageId = MessageId.newId();
consumer.runOnce(messageId, "order-projection", NOW, effects::incrementAndGet);
InboxOutcome<Integer> other =
consumer.runOnce(messageId, "billing-projection", NOW, effects::incrementAndGet);
assertThat(other.processed()).isTrue();
assertThat(effects.get()).isEqualTo(2);
}
@Test
void theReservationAndTheSideEffectShareOneTransaction() {
MessageId messageId = MessageId.newId();
consumer.runOnce(messageId, "order-projection", NOW, () -> transactions.depthDuringWork);
assertThat(transactions.transactions).isEqualTo(1);
assertThat(transactions.depthDuringWork).isEqualTo(1);
}
@Test
void aProcessedMessageIsVisibleToTheRepositoryQuery() {
MessageId messageId = MessageId.newId();
consumer.runOnce(messageId, "order-projection", NOW, () -> "done");
assertThat(inbox.isProcessed(messageId, "order-projection")).isTrue();
assertThat(inbox.isProcessed(messageId, "billing-projection")).isFalse();
}
@Test
void retentionPruningRemovesOldRows() {
consumer.runOnce(MessageId.newId(), "order-projection", NOW, () -> "done");
assertThat(inbox.purgeProcessedBefore(NOW.plusSeconds(1))).isEqualTo(1);
assertThat(inbox.size()).isZero();
}
}
/** A deterministic inbox with the composite-key uniqueness the pattern relies on. */
final class InMemoryInbox implements InboxRepository {
private final Set<String> reserved = new LinkedHashSet<>();
@Override
public boolean reserve(MessageId messageId, String consumerId, Instant now) {
return reserved.add(key(messageId, consumerId));
}
@Override
public boolean isProcessed(MessageId messageId, String consumerId) {
return reserved.contains(key(messageId, consumerId));
}
@Override
public int purgeProcessedBefore(Instant processedBefore, int limit) {
return Math.min(purgeProcessedBefore(processedBefore), limit);
}
@Override
public int purgeProcessedBefore(Instant processedBefore) {
int removed = reserved.size();
reserved.clear();
return removed;
}
int size() {
return reserved.size();
}
private static String key(MessageId messageId, String consumerId) {
return messageId.value() + "|" + consumerId;
}
}
/** Records how many transactions were opened and how deeply they nested. */
final class SingleTransactionRunner implements IdempotentConsumer.TransactionRunner {
int transactions;
int depthDuringWork;
private int depth;
@Override
public <T> T inTransaction(Supplier<T> work) {
transactions++;
depth++;
try {
depthDuringWork = depth;
return work.get();
} finally {
depth--;
}
}
}
@@ -0,0 +1,158 @@
package dev.caskeleton.messaging.inbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import dev.caskeleton.messaging.reliability.InboxRepository;
import dev.caskeleton.messaging.reliability.InboxResult;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
class InboxOperationsTest {
private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z");
/** An inbox that remembers reservations and records the cutoffs cleanup asked for. */
private static final class InMemoryInbox implements InboxRepository {
private final Set<String> reserved = new HashSet<>();
private final List<Instant> cutoffs = new ArrayList<>();
private final List<Integer> deletions;
private int pass;
private InMemoryInbox(List<Integer> deletions) {
this.deletions = deletions;
}
@Override
public boolean reserve(MessageId messageId, String consumerId, Instant now) {
return reserved.add(messageId.value() + "|" + consumerId);
}
@Override
public boolean isProcessed(MessageId messageId, String consumerId) {
return reserved.contains(messageId.value() + "|" + consumerId);
}
@Override
public int purgeProcessedBefore(Instant processedBefore, int limit) {
return Math.min(purgeProcessedBefore(processedBefore), limit);
}
@Override
public int purgeProcessedBefore(Instant processedBefore) {
cutoffs.add(processedBefore);
return pass < deletions.size() ? deletions.get(pass++) : 0;
}
}
private static InboxRetentionPolicy policy(Duration retention, Duration window) {
return new InboxRetentionPolicy(retention, window);
}
@Test
void retentionShorterThanTheRedeliveryWindowIsRefused() {
assertThatThrownBy(() -> policy(Duration.ofHours(1), Duration.ofHours(6)).validate())
.as("a pruned row lets a late redelivery apply its effect a second time")
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("twice");
}
@Test
void retentionAtTheSafetyFactorIsAccepted() {
assertThatCode(() -> policy(Duration.ofHours(12), Duration.ofHours(6)).validate())
.doesNotThrowAnyException();
}
@Test
void theRequiredRetentionScalesWithTheWindow() {
assertThat(policy(Duration.ofDays(30), Duration.ofDays(2)).required())
.isEqualTo(Duration.ofDays(4));
}
@Test
void aCleanupJobRefusesToStartUnderAnUnsafeRetention() {
assertThatThrownBy(
() ->
new InboxCleanupJob(
new InMemoryInbox(List.of(0)),
policy(Duration.ofMinutes(1), Duration.ofHours(1)),
5))
.as("dutifully deleting under a bad policy would create the bug the inbox prevents")
.isInstanceOf(MessagingConfigurationException.class);
}
@Test
void cleanupDeletesInBoundedBatches() {
InMemoryInbox inbox = new InMemoryInbox(List.of(1000, 500));
int removed =
new InboxCleanupJob(inbox, policy(Duration.ofDays(7), Duration.ofDays(1)), 10).runOnce(NOW);
assertThat(removed).isEqualTo(1500);
assertThat(inbox.cutoffs).hasSize(3);
}
@Test
void cleanupHonoursTheBatchCeilingSoItCannotRunForever() {
InMemoryInbox inbox = new InMemoryInbox(List.of(1000, 1000, 1000, 1000, 1000, 1000));
new InboxCleanupJob(inbox, policy(Duration.ofDays(7), Duration.ofDays(1)), 2).runOnce(NOW);
assertThat(inbox.cutoffs).hasSize(2);
}
@Test
void theSameMessageIsAppliedOncePerConsumerNotOncePerMessage() {
InMemoryInbox inbox = new InMemoryInbox(List.of());
IdempotentConsumer consumer = new IdempotentConsumer(inbox, new DirectRunner());
MessageId messageId = MessageId.newId();
InboxOutcome<String> first = consumer.runOnce(messageId, "billing", NOW, () -> "charged");
InboxOutcome<String> second = consumer.runOnce(messageId, "analytics", NOW, () -> "counted");
assertThat(first.processed()).isTrue();
assertThat(second.processed())
.as("two independent consumers are each entitled to apply their own effect once")
.isTrue();
}
@Test
void aRedeliveryToTheSameConsumerIsSuppressed() {
InMemoryInbox inbox = new InMemoryInbox(List.of());
IdempotentConsumer consumer = new IdempotentConsumer(inbox, new DirectRunner());
MessageId messageId = MessageId.newId();
consumer.runOnce(messageId, "billing", NOW, () -> "charged");
InboxOutcome<String> redelivery = consumer.runOnce(messageId, "billing", NOW, () -> "charged");
assertThat(redelivery.processed()).isFalse();
assertThat(redelivery.result()).isEmpty();
}
@Test
void anAlreadyAppliedMessageIsSafeToSettleButAClaimedOneIsNot() {
assertThat(InboxResult.APPLIED.isSafeToSettle()).isTrue();
assertThat(InboxResult.ALREADY_APPLIED.isSafeToSettle()).isTrue();
assertThat(InboxResult.CLAIMED_ELSEWHERE.isSafeToSettle())
.as("the other transaction may still roll back, and this is the last copy")
.isFalse();
}
/** Runs the work inline; the real runner opens a database transaction. */
private static final class DirectRunner implements IdempotentConsumer.TransactionRunner {
@Override
public <T> T inTransaction(java.util.function.Supplier<T> work) {
return work.get();
}
}
}
@@ -0,0 +1,203 @@
package dev.caskeleton.messaging.inbox;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.testkit.DockerAvailability;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicInteger;
import javax.sql.DataSource;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.postgresql.ds.PGSimpleDataSource;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.postgresql.PostgreSQLContainer;
/**
* Certifies the inbox against a real PostgreSQL.
*
* <p>The whole pattern rests on a uniqueness constraint and a shared transaction. Both are database
* behaviours: a double can be written to agree with them, and a real one either enforces them or
* does not.
*
* <p>The last test is the one that matters most. It commits an inbox reservation and a business
* write together, then rolls a second attempt back, and asserts that the side effect did not happen
* twice and the reservation did not survive the rollback.
*/
@Testcontainers
@EnabledIf("dockerAvailable")
class InboxPostgresIT {
private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z");
@Container
private static final PostgreSQLContainer POSTGRES =
new PostgreSQLContainer("postgres:16-alpine")
.withDatabaseName("messaging")
.withUsername("messaging")
.withPassword("messaging");
private DataSource dataSource;
private org.springframework.transaction.support.TransactionTemplate transactions;
private JdbcInboxRepository repository;
static boolean dockerAvailable() {
return DockerAvailability.isAvailable();
}
@BeforeEach
void migrate() throws SQLException, IOException {
dataSource = dataSource();
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("DROP TABLE IF EXISTS messaging_inbox");
statement.execute("DROP TABLE IF EXISTS projections");
statement.execute(migration());
statement.execute("CREATE TABLE projections (id TEXT PRIMARY KEY, applied INT NOT NULL)");
}
repository = new JdbcInboxRepository(dataSource);
// A real Spring transaction, because the port's contract is about joining one. The previous
// tests called the Connection overload directly, which proved that overload works and said
// nothing about the interface method every consumer actually calls.
transactions =
new org.springframework.transaction.support.TransactionTemplate(
new org.springframework.jdbc.datasource.DataSourceTransactionManager(dataSource));
}
@Test
void theFirstReservationSucceedsAndTheSecondDoesNot() {
MessageId messageId = MessageId.newId();
assertThat(inTransaction(() -> repository.reserve(messageId, "order-projection", NOW)))
.isTrue();
assertThat(inTransaction(() -> repository.reserve(messageId, "order-projection", NOW)))
.isFalse();
}
@Test
void twoConsumersEachReserveTheSameMessageOnce() {
MessageId messageId = MessageId.newId();
assertThat(inTransaction(() -> repository.reserve(messageId, "order-projection", NOW)))
.isTrue();
assertThat(inTransaction(() -> repository.reserve(messageId, "billing-projection", NOW)))
.isTrue();
assertThat(inTransaction(() -> repository.reserve(messageId, "order-projection", NOW)))
.isFalse();
}
@Test
void aProcessedMessageIsVisibleToTheQuery() {
MessageId messageId = MessageId.newId();
inTransaction(() -> repository.reserve(messageId, "order-projection", NOW));
assertThat(repository.isProcessed(messageId, "order-projection")).isTrue();
assertThat(repository.isProcessed(messageId, "billing-projection")).isFalse();
}
@Test
void aRedeliveryDoesNotApplyTheSideEffectTwice() throws SQLException {
MessageId messageId = MessageId.newId();
AtomicInteger applied = new AtomicInteger();
handle(messageId, applied);
handle(messageId, applied);
assertThat(applied.get()).as("the handler ran once").isEqualTo(1);
assertThat(projectionCount("o-1")).isEqualTo(1);
}
@Test
void aRolledBackTransactionLeavesNoReservationAndNoSideEffect() throws SQLException {
MessageId messageId = MessageId.newId();
// Through the interface method and a real Spring transaction. This is the path a consumer
// takes; the old version called the Connection overload, which is the one path that was never
// in doubt.
try {
transactions.executeWithoutResult(
status -> {
assertThat(repository.reserve(messageId, "order-projection", NOW)).isTrue();
new org.springframework.jdbc.core.JdbcTemplate(dataSource)
.execute("INSERT INTO projections (id, applied) VALUES ('o-2', 1)");
status.setRollbackOnly();
});
} catch (RuntimeException rolledBack) {
// setRollbackOnly is the mechanism; an UnexpectedRollbackException is not a failure here.
}
assertThat(repository.isProcessed(messageId, "order-projection"))
.as("the reservation must not outlive the transaction that made it")
.isFalse();
assertThat(projectionCount("o-2")).isZero();
}
@Test
void retentionRemovesOldRows() {
MessageId purged = MessageId.newId();
inTransaction(() -> repository.reserve(purged, "order-projection", NOW));
assertThat(repository.purgeProcessedBefore(NOW.plusSeconds(1))).isEqualTo(1);
}
/** Reserves and writes inside one Spring transaction, exactly as an idempotent consumer must. */
private void handle(MessageId messageId, AtomicInteger applied) {
transactions.executeWithoutResult(
status -> {
if (!repository.reserve(messageId, "order-projection", NOW)) {
status.setRollbackOnly();
return;
}
new org.springframework.jdbc.core.JdbcTemplate(dataSource)
.execute("INSERT INTO projections (id, applied) VALUES ('o-1', 1)");
applied.incrementAndGet();
});
}
private <T> T inTransaction(java.util.function.Supplier<T> work) {
return transactions.execute(status -> work.get());
}
private int projectionCount(String id) throws SQLException {
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement("SELECT count(*) FROM projections WHERE id = ?")) {
statement.setString(1, id);
try (ResultSet results = statement.executeQuery()) {
results.next();
return results.getInt(1);
}
}
}
private static DataSource dataSource() {
PGSimpleDataSource source = new PGSimpleDataSource();
source.setUrl(POSTGRES.getJdbcUrl());
source.setUser(POSTGRES.getUsername());
source.setPassword(POSTGRES.getPassword());
return source;
}
private static String migration() throws IOException {
try (InputStream stream =
InboxPostgresIT.class
.getClassLoader()
.getResourceAsStream("db/migration/messaging/V2__messaging_inbox.sql")) {
if (stream == null) {
throw new IOException("the inbox migration is missing from the classpath");
}
return new String(stream.readAllBytes(), StandardCharsets.UTF_8);
}
}
}
@@ -0,0 +1,98 @@
package dev.caskeleton.messaging.inbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.MessageId;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import java.time.Instant;
import javax.sql.DataSource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* What {@code reserve(...)} does when there is no transaction to join.
*
* <p>{@code IdempotentConsumer} calls this inside its transaction runner, and the implementation
* opened a raw connection that auto-commits. The reservation therefore survived a rollback of the
* side effect it was guarding: the message counts as processed, the work never happened, and
* redelivery is refused because the inbox row is already there.
*
* <p>Hermetic: the refusal has to happen before any connection is requested, and the data source
* below fails the test by being asked for one.
*/
class JdbcInboxTransactionRequirementTest {
/** A data source that fails the test by being used: the refusal must precede any connection. */
private final DataSource dataSource = new RefusingDataSource();
private final JdbcInboxRepository repository = new JdbcInboxRepository(dataSource);
@AfterEach
void clearTransactionState() {
TransactionSynchronizationManager.clear();
if (TransactionSynchronizationManager.hasResource(dataSource)) {
TransactionSynchronizationManager.unbindResource(dataSource);
}
}
@Test
@DisplayName("reserving outside a transaction is refused before a connection is opened")
void reservingOutsideATransactionIsRefused() {
assertThatThrownBy(() -> repository.reserve(MessageId.newId(), "order-projection", NOW))
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("requires an active transaction");
}
@Test
@DisplayName("a read-only transaction is refused")
void aReadOnlyTransactionIsRefused() {
TransactionSynchronizationManager.setActualTransactionActive(true);
TransactionSynchronizationManager.setCurrentTransactionReadOnly(true);
assertThatThrownBy(() -> repository.reserve(MessageId.newId(), "order-projection", NOW))
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("read-only");
}
@Test
@DisplayName("a transaction bound to another DataSource is refused")
void aTransactionOnAnotherDataSourceIsRefused() {
TransactionSynchronizationManager.setActualTransactionActive(true);
assertThatThrownBy(() -> repository.reserve(MessageId.newId(), "order-projection", NOW))
.as("two DataSources means two commits, which is the atomicity this exists to provide")
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("bound to this DataSource");
}
@Test
@DisplayName("the refusal names a code an operator can search for")
void theRefusalNamesACode() {
assertThatThrownBy(() -> repository.reserve(MessageId.newId(), "order-projection", NOW))
.isInstanceOfSatisfying(
MessagingConfigurationException.class,
failure ->
assertThat(failure.failure().code()).isEqualTo("INBOX_TRANSACTION_REQUIRED"));
}
private static final Instant NOW = Instant.parse("2026-08-14T00:00:00Z");
/** Throws if anything asks it for a connection. */
private static final class RefusingDataSource
extends org.springframework.jdbc.datasource.AbstractDataSource {
@Override
public java.sql.Connection getConnection() {
throw new AssertionError(
"the refusal must happen before a connection is requested; opening one is the defect");
}
@Override
public java.sql.Connection getConnection(String username, String password) {
return getConnection();
}
}
}