review-followup Wave 3 라운드 3(P21): messaging 플랫폼 — Kafka 소비(MessageHandler 하나), API 정리

- 결정 10: consume 계약을 `MessageHandler<T>` 하나로, starter-kafka가 consumer 조립(handler bean이 있으면 켜짐,
  `app.messaging.enabled=false`로 끔). 오프셋은 handler Success(inbox면 트랜잭션 커밋) 뒤 또는 DLQ 쓰기 확인 뒤에만 커밋,
  auto-commit 금지, `read_committed`, 재시도 소진 → DLQ(없으면 멈춤) — Kafka+PG로 왕복·중복 제거·DLQ 검증
- 미사용 API 타입·Blocking/Reactive/Batch facade·reactor api 노출 삭제, `PublishResult` 정적 factory,
  `MessagingCapabilities` → EnumSet, API leaf 병합(core-api+schema-api, admin-api+admin-runtime), starter god config 분해,
  Kafka broker 설정은 starter-kafka로, 등급 용어 정리
- 결함 수정: Retry 응답이 시도 횟수를 세지 않아 partition 정지(P21-new-1), deliveryAttempt 항상 1(P21-new-2)
- 통합: app-bootstrap `MessagingPublicSurfaceContractTest` 기대값을 P21 변경에 맞춤, starter-kafka에 `api kafka-clients`

검증: ./gradlew check architectureCheck verifyDependencyLocks :app-bootstrap:verifyEnvKeys :app-bootstrap:integrationTest
:sample-portfolio:integrationTest :messaging:messaging-spring-boot-starter:integrationTest
:messaging:messaging-reliability-jdbc-postgresql:integrationTest mainCheck --continue 통과(812 task)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-29 13:29:46 +09:00
co-authored by Claude Opus 5.5
parent 6397f52dc8
commit 763392c8b2
188 changed files with 3405 additions and 4015 deletions
@@ -1,110 +1,255 @@
package dev.caskeleton.messaging.runtime;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.MessageType;
import dev.caskeleton.messaging.api.delivery.DeliveryContext;
import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee;
import dev.caskeleton.messaging.api.delivery.HandleResult;
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
import dev.caskeleton.messaging.api.delivery.MessageHandler;
import dev.caskeleton.messaging.api.error.FailureCategory;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import dev.caskeleton.messaging.api.publish.PublishCompletion;
import dev.caskeleton.messaging.api.settlement.SettlementResult;
import dev.caskeleton.messaging.policy.DestinationProfile;
import dev.caskeleton.messaging.schema.EncodedMessage;
import dev.caskeleton.messaging.schema.MessageCodec;
import dev.caskeleton.messaging.schema.MessageCodecRegistry;
import dev.caskeleton.messaging.transport.TransportDelivery;
import java.time.Duration;
import java.time.InstantSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* Turns one handler outcome into exactly one broker settlement.
* Turns one still-encoded delivery into a typed {@link MessageHandler} call and exactly one broker
* settlement.
*
* <p>Nothing connected {@code HandleResult} to a settlement. Each broker adapter decided for itself
* what a retry or a dead-letter meant, so "the platform decides when and in what order the
* settlement happens" — the comment on {@code TransportSettlement} — described a decision nobody
* made in one place.
* <p>This is the consume path the platform had three half-contracts for and no assembly (S7-#2): a
* typed {@code MessageHandler} nothing called, a processor that took an untyped function, and an
* inbox handler with its own signature. There is now one handler contract, and this class is the
* one place that decodes for it, calls it, and settles.
*
* <p>Two rules are enforced here rather than left to each adapter:
* <p>Rules enforced here rather than left to each adapter:
*
* <ul>
* <li><strong>One terminal call.</strong> A delivery is acknowledged, requeued or discarded once.
* A second call is a programming error, not something to let through: acknowledging after a
* requeue tells the broker the message is done while a copy is already in flight.
* <li><strong>Dead-letter before acknowledgement.</strong> The source is acknowledged only after
* the dead-letter publish is confirmed. Acknowledging first and publishing afterwards loses
* the message whenever the second step fails, which is exactly when it matters.
* Acknowledging after a requeue tells the broker the message is done while a copy is already
* in flight.
* <li><strong>Acknowledge only after success.</strong> {@code Success} acknowledges; a handler
* that throws, fails its stage or returns nothing is requeued, not discarded.
* <li><strong>Dead letter before acknowledgement.</strong> The source is acknowledged only after
* the dead-letter publish is confirmed; an unconfirmed one requeues, because a duplicate is
* the recoverable half of that choice.
* <li><strong>Discard only where the profile allows it.</strong> {@code Reject} discards on an
* {@code AT_MOST_ONCE} destination and is dead-lettered everywhere else (design §19.2).
* <li><strong>Undecodable is not retryable.</strong> A message whose type has no handler, or
* whose payload the codec refuses, is dead-lettered rather than retried forever.
* </ul>
*
* <p>How many times a requeued delivery comes back, and what happens when the attempts run out, is
* the transport's retry policy — {@code requeue} is a request, and the Kafka consumer counts it.
*/
public final class DefaultDeliveryProcessor {
private final Function<MessageEnvelope<EncodedMessage>, HandleResult> handler;
private final DestinationProfile profile;
private final Map<MessageType, MessageHandler<?>> handlers;
private final MessageCodecRegistry codecs;
private final DeadLetterPublisher deadLetters;
private final String consumerId;
private final InstantSource clock;
private final Duration retryDelay;
/**
* Creates a processor for one destination.
*
* @param profile the destination being consumed
* @param handlers the handlers for that destination, at most one per message type
* @param codecs decodes payloads by content type
* @param deadLetters publishes a delivery to the destination's dead-letter destination
* @param consumerId the stable, low-cardinality consumer identity handlers see
* @param clock the clock handler deadlines are measured on
*/
public DefaultDeliveryProcessor(
Function<MessageEnvelope<EncodedMessage>, HandleResult> handler,
DestinationProfile profile,
List<? extends MessageHandler<?>> handlers,
MessageCodecRegistry codecs,
DeadLetterPublisher deadLetters,
Duration retryDelay) {
this.handler = Objects.requireNonNull(handler, "handler must not be null");
String consumerId,
InstantSource clock) {
this.profile = Objects.requireNonNull(profile, "profile must not be null");
this.codecs = Objects.requireNonNull(codecs, "codecs must not be null");
this.deadLetters = Objects.requireNonNull(deadLetters, "deadLetters must not be null");
this.retryDelay = Objects.requireNonNull(retryDelay, "retryDelay must not be null");
if (retryDelay.isNegative()) {
throw new IllegalArgumentException("a retry delay must not be negative");
this.clock = Objects.requireNonNull(clock, "clock must not be null");
if (consumerId == null || consumerId.isBlank()) {
throw new IllegalArgumentException("consumerId must not be blank");
}
this.consumerId = consumerId;
Map<MessageType, MessageHandler<?>> byType = new HashMap<>();
for (MessageHandler<?> handler : Objects.requireNonNull(handlers, "handlers")) {
if (!handler.destination().name().equals(profile.name())) {
throw new IllegalArgumentException(
"handler for "
+ handler.destination().name().value()
+ " cannot consume "
+ profile.name().value());
}
if (byType.put(handler.destination().messageType(), handler) != null) {
throw new IllegalArgumentException(
"destination "
+ profile.name().value()
+ " has two handlers for "
+ handler.destination().messageType().value()
+ "; which one runs would depend on bean order");
}
}
if (byType.isEmpty()) {
throw new IllegalArgumentException("a processor needs at least one handler");
}
this.handlers = Map.copyOf(byType);
}
/**
* Handles one delivery and settles it once.
*
* @return a stage completing with the settlement the broker performed
* @param delivery the still-encoded delivery
* @return a stage completing once the settlement call has returned
*/
public CompletionStage<SettlementResult> process(TransportDelivery delivery) {
public CompletionStage<Void> process(TransportDelivery delivery) {
Objects.requireNonNull(delivery, "delivery must not be null");
OneShotSettlement settlement = new OneShotSettlement(delivery);
HandleResult result;
try {
result = handler.apply(delivery.envelope());
} catch (RuntimeException handlerFailed) {
// A handler that threw is a retry, not a discard. Treating an exception as "this message is
// undeliverable" is how a transient bug in one consumer silently drops a day of traffic —
// and it is exactly what the Rabbit consumer did by folding handler exceptions into its
// deserialization-failure path.
return settlement.requeue(retryDelay);
MessageEnvelope<EncodedMessage> envelope = delivery.envelope();
MessageHandler<?> handler = handlers.get(envelope.messageType());
if (handler == null) {
return deadLetter(
delivery,
settlement,
FailureDescriptor.of(
FailureCategory.DESERIALIZATION,
"NO_HANDLER_FOR_MESSAGE_TYPE",
"no handler is registered for this message type on this destination"));
}
if (result == null) {
return settlement.requeue(retryDelay);
return dispatch(handler, delivery, settlement);
}
private <T> CompletionStage<Void> dispatch(
MessageHandler<T> handler, TransportDelivery delivery, OneShotSettlement settlement) {
MessageEnvelope<EncodedMessage> envelope = delivery.envelope();
T payload;
try {
MessageCodec codec =
codecs
.find(envelope.contentType())
.orElseThrow(
() ->
new IllegalStateException(
"no codec for content type " + envelope.contentType().value()));
payload =
codec.decode(
envelope.messageType(),
envelope.schemaVersion(),
envelope.payload(),
handler.destination().payloadType());
} catch (RuntimeException undecodable) {
return deadLetter(
delivery,
settlement,
new FailureDescriptor(
FailureCategory.DESERIALIZATION,
"PAYLOAD_UNDECODABLE",
false,
"the payload could not be decoded into the handler's type",
Optional.of(undecodable.getClass().getSimpleName())));
}
Duration timeout = profile.consumer().handlerTimeout();
MessageDelivery<T> typed =
new MessageDelivery<>(
envelope.withPayload(payload),
delivery.metadata(),
new DeliveryContext(clock.instant().plus(timeout), false, consumerId));
CompletionStage<HandleResult> outcome;
try {
outcome = handler.handle(typed);
} catch (RuntimeException handlerFailed) {
// A handler that threw is a retry, not a discard. Treating an exception as "this message is
// undeliverable" is how a transient bug in one consumer silently drops a day of traffic.
return settlement.requeue();
}
if (outcome == null) {
return settlement.requeue();
}
return outcome
.handle(
(result, failure) ->
failure == null ? Optional.ofNullable(result) : Optional.<HandleResult>empty())
.thenCompose(
result ->
result.isEmpty()
? settlement.requeue()
: settle(result.get(), delivery, settlement));
}
private CompletionStage<Void> settle(
HandleResult result, TransportDelivery delivery, OneShotSettlement settlement) {
return switch (result) {
case HandleResult.Success ignored -> settlement.acknowledge();
case HandleResult.Retry ignored -> settlement.requeue(retryDelay);
case HandleResult.Reject ignored -> settlement.discard();
case HandleResult.Retry ignored -> settlement.requeue();
case HandleResult.Reject reject ->
profile.deliveryGuarantee() == DeliveryGuarantee.AT_MOST_ONCE
? settlement.discard()
// Discarding on an at-least-once destination would drop a message the profile
// promised to deliver, so the rejection is kept where someone can look at it.
: deadLetter(delivery, settlement, reject.failure());
case HandleResult.DeadLetter deadLetter ->
deadLetters
.publish(delivery.envelope(), deadLetter.failure())
.thenCompose(
completion ->
completion == PublishCompletion.CONFIRMED
// Confirmed: the message exists somewhere else, so removing it here is
// safe.
? settlement.acknowledge()
// Not confirmed — rejected or ambiguous. Requeueing risks a duplicate;
// acknowledging loses the message outright, and a duplicate is the
// recoverable half of that choice.
: settlement.requeue(retryDelay));
deadLetter(delivery, settlement, deadLetter.failure());
};
}
private CompletionStage<Void> deadLetter(
TransportDelivery delivery, OneShotSettlement settlement, FailureDescriptor failure) {
if (!profile.deadLetter().enabled()) {
// Nowhere to put it. Requeueing keeps the only copy; the transport's retry budget decides
// whether the partition then parks it or keeps it.
return settlement.requeue();
}
MessageDelivery<EncodedMessage> encoded =
new MessageDelivery<>(
delivery.envelope(),
delivery.metadata(),
new DeliveryContext(clock.instant(), false, consumerId));
CompletionStage<PublishCompletion> published;
try {
published = deadLetters.publish(encoded, failure);
} catch (RuntimeException publishFailed) {
return settlement.requeue();
}
return published
.handle((completion, error) -> error == null && completion == PublishCompletion.CONFIRMED)
.thenCompose(confirmed -> confirmed ? settlement.acknowledge() : settlement.requeue());
}
/** Publishes a delivery that cannot be handled to its dead-letter destination. */
@FunctionalInterface
public interface DeadLetterPublisher {
/** Publishes and reports what the broker confirmed. */
/**
* Publishes and reports what the broker confirmed.
*
* @param delivery the delivery, still encoded
* @param failure why it is being dead-lettered
* @return a stage completing with the publish completion
*/
CompletionStage<PublishCompletion> publish(
MessageEnvelope<EncodedMessage> envelope, FailureDescriptor failure);
MessageDelivery<EncodedMessage> delivery, FailureDescriptor failure);
}
/** A settlement that can be used once. */
@@ -118,20 +263,21 @@ public final class DefaultDeliveryProcessor {
this.delivery = delivery;
}
private CompletionStage<SettlementResult> acknowledge() {
private CompletionStage<Void> acknowledge() {
return once("acknowledge", () -> delivery.settlement().acknowledge());
}
private CompletionStage<SettlementResult> requeue(Duration delay) {
return once("requeue", () -> delivery.settlement().requeue(delay));
private CompletionStage<Void> requeue() {
// The delay is the transport's retry policy; zero asks for "as soon as that policy allows".
return once("requeue", () -> delivery.settlement().requeue(Duration.ZERO));
}
private CompletionStage<SettlementResult> discard() {
private CompletionStage<Void> discard() {
return once("discard", () -> delivery.settlement().discard());
}
private CompletionStage<SettlementResult> once(
String what, java.util.function.Supplier<CompletionStage<SettlementResult>> call) {
private CompletionStage<Void> once(
String what, Supplier<CompletionStage<SettlementResult>> call) {
if (!settled.compareAndSet(false, true)) {
return CompletableFuture.failedFuture(
new IllegalStateException(
@@ -139,17 +285,7 @@ public final class DefaultDeliveryProcessor {
+ what
+ " would tell the broker something the first call already contradicted"));
}
return call.get();
return call.get().thenApply(ignored -> null);
}
}
/** A descriptor for a handler that returned nothing, kept out of the hot path. */
static FailureDescriptor missingResult() {
return new FailureDescriptor(
FailureCategory.PROCESSING_TRANSIENT,
"HANDLER_RETURNED_NOTHING",
true,
"the handler returned no result, which is treated as a retry rather than a discard",
Optional.empty());
}
}
@@ -5,11 +5,8 @@ import dev.caskeleton.messaging.api.destination.MessageDestination;
import dev.caskeleton.messaging.api.error.FailureCategory;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import dev.caskeleton.messaging.api.publish.MessagePublisher;
import dev.caskeleton.messaging.api.publish.PublishCompletion;
import dev.caskeleton.messaging.api.publish.PublishEvidence;
import dev.caskeleton.messaging.api.publish.PublishOptions;
import dev.caskeleton.messaging.api.publish.PublishResult;
import dev.caskeleton.messaging.api.publish.RoutingOutcome;
import dev.caskeleton.messaging.policy.DestinationProfile;
import dev.caskeleton.messaging.policy.MessagingAdmissionController;
import dev.caskeleton.messaging.schema.EncodedMessage;
@@ -288,7 +285,12 @@ public final class DefaultMessagePublisher implements MessagePublisher, EncodedM
*/
private void requireSupportedOptions(DestinationProfile profile, PublishOptions options) {
if (options.deduplication().isPresent()
&& !transport.capabilities(profile.name()).capabilities().deduplicatedPublish()) {
&& !transport
.capabilities(profile.name())
.capabilities()
.supports(
dev.caskeleton.messaging.api.destination.MessagingCapabilities.Capability
.DEDUPLICATED_PUBLISH)) {
throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException(
"PUBLISH_DEDUPLICATION_UNSUPPORTED",
"destination '"
@@ -332,27 +334,13 @@ public final class DefaultMessagePublisher implements MessagePublisher, EncodedM
private CompletionStage<PublishResult> refused(FailureDescriptor failure, long startedAt) {
return CompletableFuture.completedFuture(
new PublishResult(
PublishCompletion.REJECTED,
PublishEvidence.notTransmitted(),
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
elapsedSince(startedAt),
Optional.of(failure)));
PublishResult.rejected(elapsedSince(startedAt), failure));
}
private PublishResult ambiguousResult(String code, String reason, long startedAt) {
return new PublishResult(
PublishCompletion.AMBIGUOUS,
PublishEvidence.ambiguous(),
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
return PublishResult.ambiguous(
elapsedSince(startedAt),
Optional.of(
new FailureDescriptor(
FailureCategory.AMBIGUOUS, code, true, reason, Optional.empty())));
new FailureDescriptor(FailureCategory.AMBIGUOUS, code, true, reason, Optional.empty()));
}
/**
@@ -1,6 +1,7 @@
package dev.caskeleton.messaging.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.messaging.api.ContentType;
import dev.caskeleton.messaging.api.MessageEnvelope;
@@ -9,123 +10,318 @@ import dev.caskeleton.messaging.api.MessageType;
import dev.caskeleton.messaging.api.ProducerId;
import dev.caskeleton.messaging.api.SchemaVersion;
import dev.caskeleton.messaging.api.TraceContext;
import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee;
import dev.caskeleton.messaging.api.delivery.DeliveryMetadata;
import dev.caskeleton.messaging.api.delivery.HandleResult;
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
import dev.caskeleton.messaging.api.delivery.MessageHandler;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.destination.MessageDestination;
import dev.caskeleton.messaging.api.error.FailureCategory;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import dev.caskeleton.messaging.api.header.MessageHeaders;
import dev.caskeleton.messaging.api.publish.PublishCompletion;
import dev.caskeleton.messaging.api.settlement.SettlementResult;
import dev.caskeleton.messaging.policy.DeadLetterPolicy;
import dev.caskeleton.messaging.policy.DestinationProfile;
import dev.caskeleton.messaging.schema.EncodedMessage;
import dev.caskeleton.messaging.schema.MessageCodec;
import dev.caskeleton.messaging.transport.TransportDelivery;
import dev.caskeleton.messaging.transport.TransportSettlement;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.InstantSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* One handler outcome, one settlement.
* One typed handler, one outcome, one settlement.
*
* <p>Nothing turned a {@code HandleResult} into a settlement: each broker adapter decided for
* itself, and the Rabbit consumer folded handler exceptions into its deserialization-failure path
* and discarded them.
* <p>The processor took an untyped function and nothing assembled it; the typed {@code
* MessageHandler} had no caller (S7-#2). These tests hold the settlement rules on the one contract
* that is left.
*/
class DefaultDeliveryProcessorTest {
private static final DestinationName ORDERS = new DestinationName("order-events");
private static final MessageType CREATED = new MessageType("order.created");
private static final Instant NOW = Instant.parse("2026-08-14T00:00:00Z");
private final RecordingSettlement settlement = new RecordingSettlement();
@Test
@DisplayName("success acknowledges once")
void successAcknowledgesOnce() {
process(envelope -> new HandleResult.Success(), confirmedDeadLetters());
@DisplayName("성공하면 handler가 decode된 payload를 받고 한 번 acknowledge된다")
void aSuccessfulHandlerReceivesTheDecodedPayloadAndIsAcknowledgedOnce() {
// given
List<String> received = new ArrayList<>();
MessageHandler<String> handler =
handler(
delivery -> {
received.add(delivery.message().payload());
return HandleResult.success();
});
// when
process(handler, confirmedDeadLetters(), RuntimeFixtures.profile(ORDERS));
// then
assertThat(received).containsExactly("{\"orderId\":\"o-1\"}");
assertThat(settlement.calls()).containsExactly("acknowledge");
}
@Test
@DisplayName("retry requeues with the configured delay")
void retryRequeues() {
process(envelope -> new HandleResult.Retry(failure()), confirmedDeadLetters());
@DisplayName("Retry 결과는 requeue된다")
void aRetryResultIsRequeued() {
// when
process(
handler(delivery -> new HandleResult.Retry(failure())),
confirmedDeadLetters(),
RuntimeFixtures.profile(ORDERS));
// then
assertThat(settlement.calls()).containsExactly("requeue");
}
@Test
@DisplayName("a handler that throws is retried, not discarded")
void aThrowingHandlerIsRetried() {
@DisplayName("예외를 던진 handler는 버려지지 않고 requeue된다")
void aThrowingHandlerIsRequeuedNotDiscarded() {
// when
process(
envelope -> {
throw new IllegalStateException("a bug in the projection");
},
confirmedDeadLetters());
handler(
delivery -> {
throw new IllegalStateException("a bug in the projection");
}),
confirmedDeadLetters(),
RuntimeFixtures.profile(ORDERS));
assertThat(settlement.calls())
.as("treating an exception as undeliverable drops a day of traffic over a transient bug")
.containsExactly("requeue");
// then
assertThat(settlement.calls()).containsExactly("requeue");
}
@Test
@DisplayName("a dead letter is published before the source is acknowledged")
void aDeadLetterIsPublishedBeforeAcknowledgement() {
@DisplayName("실패로 끝난 stage를 돌려준 handler는 requeue된다")
void aHandlerWhoseStageFailsIsRequeued() {
// given
MessageHandler<String> handler =
new StringHandler(
delivery -> {
throw new UnsupportedOperationException("unused");
}) {
@Override
public CompletionStage<HandleResult> handle(MessageDelivery<String> delivery) {
return CompletableFuture.failedFuture(new IllegalStateException("database down"));
}
};
// when
process(handler, confirmedDeadLetters(), RuntimeFixtures.profile(ORDERS));
// then
assertThat(settlement.calls()).containsExactly("requeue");
}
@Test
@DisplayName("dead letter는 발행이 확인된 뒤에 source를 acknowledge한다")
void aDeadLetterIsPublishedBeforeTheSourceIsAcknowledged() {
// given
List<String> order = new ArrayList<>();
DefaultDeliveryProcessor.DeadLetterPublisher publisher =
(envelope, failure) -> {
(delivery, failure) -> {
order.add("dead-letter published");
return CompletableFuture.completedFuture(PublishCompletion.CONFIRMED);
};
settlement.recordInto(order);
process(envelope -> new HandleResult.DeadLetter(failure()), publisher);
// when
process(
handler(delivery -> new HandleResult.DeadLetter(failure())),
publisher,
RuntimeFixtures.profile(ORDERS));
// then
assertThat(order).containsExactly("dead-letter published", "acknowledge");
}
@Test
@DisplayName("an unconfirmed dead letter requeues rather than acknowledging")
void anUnconfirmedDeadLetterRequeues() {
@DisplayName("확인되지 않은 dead letter는 acknowledge하지 않고 requeue한다")
void anUnconfirmedDeadLetterIsRequeued() {
// when
process(
envelope -> new HandleResult.DeadLetter(failure()),
(envelope, failure) -> CompletableFuture.completedFuture(PublishCompletion.AMBIGUOUS));
handler(delivery -> new HandleResult.DeadLetter(failure())),
(delivery, failure) -> CompletableFuture.completedFuture(PublishCompletion.AMBIGUOUS),
RuntimeFixtures.profile(ORDERS));
assertThat(settlement.calls())
.as("acknowledging loses the message outright; a duplicate is the recoverable half")
.containsExactly("requeue");
// then
assertThat(settlement.calls()).containsExactly("requeue");
}
@Test
@DisplayName("a rejected message is discarded")
void aRejectedMessageIsDiscarded() {
process(envelope -> new HandleResult.Reject(failure()), confirmedDeadLetters());
@DisplayName("at-least-once destination의 Reject는 버리지 않고 dead letter로 보낸다")
void aRejectOnAnAtLeastOnceDestinationIsDeadLetteredNotDiscarded() {
// given
List<FailureDescriptor> deadLettered = new ArrayList<>();
// when
process(
handler(delivery -> new HandleResult.Reject(failure())),
(delivery, failure) -> {
deadLettered.add(failure);
return CompletableFuture.completedFuture(PublishCompletion.CONFIRMED);
},
RuntimeFixtures.profile(ORDERS));
// then
assertThat(deadLettered).containsExactly(failure());
assertThat(settlement.calls()).containsExactly("acknowledge");
}
@Test
@DisplayName("at-most-once destination의 Reject는 discard된다")
void aRejectOnAnAtMostOnceDestinationIsDiscarded() {
// when
process(
handler(delivery -> new HandleResult.Reject(failure())),
confirmedDeadLetters(),
atMostOnce(RuntimeFixtures.profile(ORDERS)));
// then
assertThat(settlement.calls()).containsExactly("discard");
}
@Test
@DisplayName("a handler returning nothing is retried")
void aHandlerReturningNothingIsRetried() {
process(envelope -> null, confirmedDeadLetters());
@DisplayName("handler가 없는 message type은 재시도하지 않고 dead letter로 보낸다")
void aMessageTypeWithNoHandlerIsDeadLetteredInsteadOfRetried() {
// given
List<String> codes = new ArrayList<>();
MessageHandler<String> otherType =
new StringHandler(
new MessageDestination<>(ORDERS, new MessageType("order.cancelled"), String.class),
delivery -> HandleResult.success());
// when
process(
otherType,
(delivery, failure) -> {
codes.add(failure.code());
return CompletableFuture.completedFuture(PublishCompletion.CONFIRMED);
},
RuntimeFixtures.profile(ORDERS));
// then
assertThat(codes).containsExactly("NO_HANDLER_FOR_MESSAGE_TYPE");
assertThat(settlement.calls()).containsExactly("acknowledge");
}
@Test
@DisplayName("dead letter destination이 없으면 dead letter 대신 requeue해 유일한 사본을 지킨다")
void withoutADeadLetterDestinationADeadLetterIsRequeuedToKeepTheOnlyCopy() {
// when
process(
handler(delivery -> new HandleResult.DeadLetter(failure())),
confirmedDeadLetters(),
withoutDeadLetter(RuntimeFixtures.profile(ORDERS)));
// then
assertThat(settlement.calls()).containsExactly("requeue");
}
@Test
@DisplayName("한 message type에 handler가 둘이면 processor를 만들 수 없다")
void twoHandlersForOneMessageTypeAreRefused() {
// given
List<MessageHandler<String>> twice =
List.of(handler(delivery -> HandleResult.success()), handler(delivery -> null));
// when
Throwable thrown =
catchThrowable(
() ->
new DefaultDeliveryProcessor(
RuntimeFixtures.profile(ORDERS),
twice,
RegisteredMessageCodecs.of(new Utf8Codec()),
confirmedDeadLetters(),
"order-projection",
InstantSource.fixed(NOW)));
// then
assertThat(thrown)
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("two handlers for order.created");
}
private void process(
java.util.function.Function<MessageEnvelope<EncodedMessage>, HandleResult> handler,
DefaultDeliveryProcessor.DeadLetterPublisher deadLetters) {
new DefaultDeliveryProcessor(handler, deadLetters, Duration.ofSeconds(5))
MessageHandler<?> handler,
DefaultDeliveryProcessor.DeadLetterPublisher deadLetters,
DestinationProfile profile) {
new DefaultDeliveryProcessor(
profile,
List.of(handler),
RegisteredMessageCodecs.of(new Utf8Codec()),
deadLetters,
"order-projection",
InstantSource.fixed(NOW))
.process(new TransportDelivery(envelope(), metadata(), settlement))
.toCompletableFuture()
.join();
}
private static MessageHandler<String> handler(
Function<MessageDelivery<String>, HandleResult> body) {
return new StringHandler(body);
}
private static DefaultDeliveryProcessor.DeadLetterPublisher confirmedDeadLetters() {
return (envelope, failure) -> CompletableFuture.completedFuture(PublishCompletion.CONFIRMED);
return (delivery, failure) -> CompletableFuture.completedFuture(PublishCompletion.CONFIRMED);
}
private static DestinationProfile atMostOnce(DestinationProfile base) {
return new DestinationProfile(
base.name(),
base.broker(),
base.kind(),
base.physical(),
base.schema(),
DeliveryGuarantee.AT_MOST_ONCE,
base.orderingScope(),
base.externalSideEffectGuarantee(),
base.producer(),
base.consumer(),
base.retry(),
base.deadLetter(),
base.payload(),
base.tier(),
base.production(),
base.keyResolverConfigured(),
base.topologyAutoCreate());
}
private static DestinationProfile withoutDeadLetter(DestinationProfile base) {
return new DestinationProfile(
base.name(),
base.broker(),
base.kind(),
base.physical(),
base.schema(),
base.deliveryGuarantee(),
base.orderingScope(),
base.externalSideEffectGuarantee(),
base.producer(),
base.consumer(),
base.retry(),
DeadLetterPolicy.disabled(),
base.payload(),
base.tier(),
base.production(),
base.keyResolverConfigured(),
base.topologyAutoCreate());
}
private static FailureDescriptor failure() {
@@ -139,21 +335,15 @@ class DefaultDeliveryProcessorTest {
private static DeliveryMetadata metadata() {
return new DeliveryMetadata(
new dev.caskeleton.messaging.api.destination.DestinationName("order-events"),
1,
false,
Optional.empty(),
Optional.empty(),
Optional.of("order-projection"),
Instant.parse("2026-08-14T00:00:00Z"));
ORDERS, 1, false, Optional.empty(), Optional.empty(), Optional.of("order-projection"), NOW);
}
private static MessageEnvelope<EncodedMessage> envelope() {
return new MessageEnvelope<>(
MessageId.newId(),
new MessageType("order.created"),
CREATED,
new SchemaVersion(1),
Instant.parse("2026-08-14T00:00:00Z"),
NOW,
Optional.empty(),
new ProducerId("orders"),
Optional.empty(),
@@ -165,7 +355,58 @@ class DefaultDeliveryProcessorTest {
TraceContext.none(),
MessageHeaders.empty(),
new EncodedMessage(
"{}".getBytes(StandardCharsets.UTF_8), ContentType.JSON, Optional.empty()));
"{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8),
ContentType.JSON,
Optional.empty()));
}
/** A handler for {@code order.created} whose body is a function. */
private static class StringHandler implements MessageHandler<String> {
private final MessageDestination<String> destination;
private final Function<MessageDelivery<String>, HandleResult> body;
StringHandler(Function<MessageDelivery<String>, HandleResult> body) {
this(new MessageDestination<>(ORDERS, CREATED, String.class), body);
}
StringHandler(
MessageDestination<String> destination,
Function<MessageDelivery<String>, HandleResult> body) {
this.destination = destination;
this.body = body;
}
@Override
public MessageDestination<String> destination() {
return destination;
}
@Override
public CompletionStage<HandleResult> handle(MessageDelivery<String> delivery) {
return CompletableFuture.completedFuture(body.apply(delivery));
}
}
/** Decodes JSON bytes to the raw string, which is all these tests need. */
private static final class Utf8Codec implements MessageCodec {
@Override
public ContentType contentType() {
return ContentType.JSON;
}
@Override
public EncodedMessage encode(MessageType type, SchemaVersion version, Object payload) {
return new EncodedMessage(
payload.toString().getBytes(StandardCharsets.UTF_8), ContentType.JSON, Optional.empty());
}
@Override
public <T> T decode(
MessageType type, SchemaVersion version, byte[] encoded, Class<T> payloadType) {
return payloadType.cast(new String(encoded, StandardCharsets.UTF_8));
}
}
/** Records which terminal call the processor made, and in what order. */
@@ -3,7 +3,7 @@ package dev.caskeleton.messaging.runtime;
import dev.caskeleton.messaging.api.ContentType;
import dev.caskeleton.messaging.api.MessageType;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.policy.CapabilityTier;
import dev.caskeleton.messaging.policy.ApiTier;
import dev.caskeleton.messaging.policy.ConsumerPolicy;
import dev.caskeleton.messaging.policy.DeadLetterPolicy;
import dev.caskeleton.messaging.policy.DestinationProfile;
@@ -36,7 +36,7 @@ final class RuntimeFixtures {
dev.caskeleton.messaging.policy.RetryPolicy.none(),
DeadLetterPolicy.to(new DestinationName("order-events-dlq")),
PayloadPolicy.defaults(),
CapabilityTier.M1,
ApiTier.M1,
false,
false,
false);