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
@@ -0,0 +1,129 @@
package dev.caskeleton.messaging.inbox;
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.MessageDestination;
import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.function.Supplier;
/**
* Runs a {@link MessageHandler} at most once per message and consumer, inside the inbox
* reservation's transaction.
*
* <p>It is a {@code MessageHandler} itself, so the consume path has one contract. It replaced an
* {@code IdempotentMessageHandler} with a different signature that nothing called (S7-#2): the
* platform wraps a handler in this when the destination's profile declares {@code
* INBOX_TRANSACTIONAL}, and the handler does not change.
*
* <p>The reservation and the handler's side effect commit together or not at all:
*
* <ul>
* <li>the message was reserved before (a redelivery) — the handler is not called and the result
* is {@code Success}, so the broker settles a message whose work is already done;
* <li>the handler answers {@code Success} — the transaction commits with the reservation;
* <li>the handler answers anything else, throws, or its stage fails — the transaction rolls back,
* the reservation with it, and the answer (or the failure) goes to the platform, which
* retries or dead-letters as it would without an inbox.
* </ul>
*
* <p>The handler's stage is awaited on the calling thread, inside the transaction. A handler that
* hands its write to another thread writes outside the transaction, and the inbox cannot protect
* that write.
*
* @param <T> the payload type
*/
public final class InboxMessageHandler<T> implements MessageHandler<T> {
private final MessageHandler<T> delegate;
private final IdempotentConsumer inbox;
private final String consumerName;
private final Supplier<Instant> clock;
/**
* Wraps a handler.
*
* @param delegate the business handler
* @param inbox the reservation-and-effect runner
* @param consumerName the consumer identity the reservation is keyed on
* @param clock supplies the reservation instant
*/
public InboxMessageHandler(
MessageHandler<T> delegate,
IdempotentConsumer inbox,
String consumerName,
Supplier<Instant> clock) {
this.delegate = Objects.requireNonNull(delegate, "delegate must not be null");
this.inbox = Objects.requireNonNull(inbox, "inbox must not be null");
this.clock = Objects.requireNonNull(clock, "clock must not be null");
if (consumerName == null || consumerName.isBlank()) {
throw new IllegalArgumentException("consumerName must not be blank");
}
this.consumerName = consumerName;
}
@Override
public MessageDestination<T> destination() {
return delegate.destination();
}
@Override
public CompletionStage<HandleResult> handle(MessageDelivery<T> delivery) {
Objects.requireNonNull(delivery, "delivery must not be null");
try {
InboxOutcome<HandleResult> outcome =
inbox.runOnce(
delivery.message().messageId(),
consumerName,
clock.get(),
() -> {
HandleResult result = answerOf(delivery);
if (!(result instanceof HandleResult.Success)) {
// Thrown, not returned: the runner rolls back only on a throw, and a reservation
// that commits without its effect suppresses the redelivery that would apply it.
throw new NotAppliedException(result);
}
return result;
});
return CompletableFuture.completedFuture(outcome.result().orElseGet(HandleResult::success));
} catch (NotAppliedException notApplied) {
return CompletableFuture.completedFuture(notApplied.result);
} catch (RuntimeException failed) {
return CompletableFuture.failedFuture(failed);
}
}
private HandleResult answerOf(MessageDelivery<T> delivery) {
CompletionStage<HandleResult> stage = delegate.handle(delivery);
if (stage == null) {
throw new IllegalStateException("the handler returned no stage");
}
try {
HandleResult result = stage.toCompletableFuture().join();
if (result == null) {
throw new IllegalStateException("the handler returned no result");
}
return result;
} catch (CompletionException failed) {
throw failed.getCause() instanceof RuntimeException cause ? cause : failed;
}
}
/** Carries a non-success answer out of the transaction so it rolls back. */
private static final class NotAppliedException extends RuntimeException {
private static final long serialVersionUID = 1L;
@SuppressWarnings("serial")
private final transient HandleResult result;
private NotAppliedException(HandleResult result) {
super(null, null, false, false);
this.result = result;
}
}
}
@@ -1,104 +0,0 @@
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 ActionFailedException(failure);
}
return InboxResult.APPLIED;
});
return CompletableFuture.completedFuture(
outcome.processed() ? HandleResult.success() : duplicateIsSuccess());
} catch (ActionFailedException 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 ActionFailedException extends RuntimeException {
private static final long serialVersionUID = 1L;
private ActionFailedException(Throwable cause) {
super(cause);
}
}
}
@@ -6,11 +6,8 @@ import dev.caskeleton.messaging.api.error.FailureCategory;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import dev.caskeleton.messaging.api.error.MessagingException;
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.reliability.OutboxLease;
import dev.caskeleton.messaging.reliability.OutboxRecord;
import dev.caskeleton.messaging.reliability.OutboxRepository;
@@ -20,7 +17,6 @@ import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Publishes outbox rows, treating an unknown outcome as retryable rather than final.
@@ -254,18 +250,12 @@ public final class OutboxRelay {
} catch (RuntimeException unknown) {
// An exception says nothing about whether the broker took the message, so the row is retried
// under the same id like any other unknown outcome — not failed, not left IN_FLIGHT.
return new PublishResult(
PublishCompletion.AMBIGUOUS,
PublishEvidence.ambiguous(),
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
return PublishResult.ambiguous(
Duration.ZERO,
Optional.of(
FailureDescriptor.of(
FailureCategory.AMBIGUOUS,
"PUBLISH_OUTCOME_UNKNOWN",
"the publisher threw " + unknown.getClass().getSimpleName())));
FailureDescriptor.of(
FailureCategory.AMBIGUOUS,
"PUBLISH_OUTCOME_UNKNOWN",
"the publisher threw " + unknown.getClass().getSimpleName()));
}
}