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,155 @@
package dev.caskeleton.messaging.runtime;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.delivery.HandleResult;
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.schema.EncodedMessage;
import dev.caskeleton.messaging.transport.TransportDelivery;
import java.time.Duration;
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;
/**
* Turns one handler outcome into 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>Two rules are 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.
* </ul>
*/
public final class DefaultDeliveryProcessor {
private final Function<MessageEnvelope<EncodedMessage>, HandleResult> handler;
private final DeadLetterPublisher deadLetters;
private final Duration retryDelay;
public DefaultDeliveryProcessor(
Function<MessageEnvelope<EncodedMessage>, HandleResult> handler,
DeadLetterPublisher deadLetters,
Duration retryDelay) {
this.handler = Objects.requireNonNull(handler, "handler 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");
}
}
/**
* Handles one delivery and settles it once.
*
* @return a stage completing with the settlement the broker performed
*/
public CompletionStage<SettlementResult> 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);
}
if (result == null) {
return settlement.requeue(retryDelay);
}
return switch (result) {
case HandleResult.Success ignored -> settlement.acknowledge();
case HandleResult.Retry ignored -> settlement.requeue(retryDelay);
case HandleResult.Reject ignored -> settlement.discard();
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));
};
}
/** Publishes a delivery that cannot be handled to its dead-letter destination. */
@FunctionalInterface
public interface DeadLetterPublisher {
/** Publishes and reports what the broker confirmed. */
CompletionStage<PublishCompletion> publish(
MessageEnvelope<EncodedMessage> envelope, FailureDescriptor failure);
}
/** A settlement that can be used once. */
private static final class OneShotSettlement {
private final TransportDelivery delivery;
private final AtomicBoolean settled = new AtomicBoolean();
private OneShotSettlement(TransportDelivery delivery) {
this.delivery = delivery;
}
private CompletionStage<SettlementResult> acknowledge() {
return once("acknowledge", () -> delivery.settlement().acknowledge());
}
private CompletionStage<SettlementResult> requeue(Duration delay) {
return once("requeue", () -> delivery.settlement().requeue(delay));
}
private CompletionStage<SettlementResult> discard() {
return once("discard", () -> delivery.settlement().discard());
}
private CompletionStage<SettlementResult> once(
String what, java.util.function.Supplier<CompletionStage<SettlementResult>> call) {
if (!settled.compareAndSet(false, true)) {
return CompletableFuture.failedFuture(
new IllegalStateException(
"this delivery has already been settled; a second "
+ what
+ " would tell the broker something the first call already contradicted"));
}
return call.get();
}
}
/** 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());
}
}
@@ -0,0 +1,313 @@
package dev.caskeleton.messaging.runtime;
import dev.caskeleton.messaging.api.MessageEnvelope;
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;
import dev.caskeleton.messaging.schema.MessageCodec;
import dev.caskeleton.messaging.schema.MessageCodecRegistry;
import dev.caskeleton.messaging.security.DestinationAccessPolicy;
import dev.caskeleton.messaging.transport.MessagingRuntimeLease;
import dev.caskeleton.messaging.transport.MessagingRuntimeRegistry;
import dev.caskeleton.messaging.transport.MessagingTransport;
import dev.caskeleton.messaging.transport.TransportPublishRequest;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.LongSupplier;
/**
* The one publish path: resolve, authorize, encode, admit, lease, send, normalize.
*
* <p>{@code MessagePublisher} was an interface with no implementation. The brokers implemented
* {@code MessagingTransport}, which takes an already-resolved profile and already-encoded bytes;
* the core auto-configuration built a dead-letter orchestrator and blocking/reactive facades on top
* of a publisher bean nothing supplied; and the admission controller, access policy, runtime
* registry and observation existed as beans that no publish ever called. An application that filled
* the gap with its own publisher would pass a context test while running none of them.
*
* <p>The order below is fixed, not composed from a map of interceptors. Each stage's position is a
* decision:
*
* <ul>
* <li>destination and access first, so an unauthorized publish never encodes a payload;
* <li>encoding before admission, because the admission bound is on bytes and the byte count is
* not known until the payload is encoded;
* <li>the runtime lease last before the send, so a rotation cannot swap the transport underneath
* a message that has already been counted against the in-flight limit.
* </ul>
*
* <p>Everything acquired is released exactly once, on every path — success, failure, exception and
* cancellation. A permit or lease that leaks on the failure path is a limiter that shrinks by one
* per failure until it stops accepting anything.
*/
public final class DefaultMessagePublisher implements MessagePublisher {
private final DestinationProfileRegistry destinations;
private final DestinationAccessPolicy access;
private final MessageCodecRegistry codecs;
private final MessagingAdmissionController admission;
private final MessagingRuntimeRegistry runtimes;
private final MessagingTransport transport;
private final LongSupplier nanoTime;
/**
* Where every publish outcome is recorded.
*
* <p>{@code MessagingObservation} existed as a bean and no publish path called it, so the
* platform's own metrics described nothing. It is a constructor argument rather than an optional
* decorator because an unobserved publish path is how "the dashboards were empty during the
* incident" happens.
*/
private final dev.caskeleton.messaging.observation.MessagingObservation observation;
public DefaultMessagePublisher(
DestinationProfileRegistry destinations,
DestinationAccessPolicy access,
MessageCodecRegistry codecs,
MessagingAdmissionController admission,
MessagingRuntimeRegistry runtimes,
MessagingTransport transport) {
this(
destinations,
access,
codecs,
admission,
runtimes,
transport,
System::nanoTime,
NO_OBSERVATION);
}
/** A no-op observation, for a deployment that has not wired metrics. */
private static final dev.caskeleton.messaging.observation.MessagingObservation NO_OBSERVATION =
new dev.caskeleton.messaging.observation.MessagingObservation() {
@Override
public void recordPublish(
dev.caskeleton.messaging.observation.MessagingTags tags, Duration elapsed) {}
@Override
public void recordDelivery(
dev.caskeleton.messaging.observation.MessagingTags tags,
Duration elapsed,
int attempt) {}
@Override
public void recordSettlement(dev.caskeleton.messaging.observation.MessagingTags tags) {}
@Override
public void recordBacklog(
dev.caskeleton.messaging.observation.MessagingTags tags, long messages) {}
@Override
public void recordDiagnostics(
dev.caskeleton.messaging.observation.MessagingTags tags,
java.util.Map<String, String> diagnostics) {}
};
/** A publisher with an injectable clock, so elapsed time is testable without sleeping. */
public DefaultMessagePublisher(
DestinationProfileRegistry destinations,
DestinationAccessPolicy access,
MessageCodecRegistry codecs,
MessagingAdmissionController admission,
MessagingRuntimeRegistry runtimes,
MessagingTransport transport,
LongSupplier nanoTime) {
this(destinations, access, codecs, admission, runtimes, transport, nanoTime, NO_OBSERVATION);
}
/** A publisher that records every outcome. */
public DefaultMessagePublisher(
DestinationProfileRegistry destinations,
DestinationAccessPolicy access,
MessageCodecRegistry codecs,
MessagingAdmissionController admission,
MessagingRuntimeRegistry runtimes,
MessagingTransport transport,
LongSupplier nanoTime,
dev.caskeleton.messaging.observation.MessagingObservation observation) {
this.observation = Objects.requireNonNull(observation, "observation must not be null");
this.destinations = Objects.requireNonNull(destinations, "destinations must not be null");
this.access = Objects.requireNonNull(access, "access must not be null");
this.codecs = Objects.requireNonNull(codecs, "codecs must not be null");
this.admission = Objects.requireNonNull(admission, "admission must not be null");
this.runtimes = Objects.requireNonNull(runtimes, "runtimes must not be null");
this.transport = Objects.requireNonNull(transport, "transport must not be null");
this.nanoTime = Objects.requireNonNull(nanoTime, "nanoTime must not be null");
}
@Override
public <T> CompletionStage<PublishResult> publish(
MessageDestination<T> destination, MessageEnvelope<T> message, PublishOptions options) {
Objects.requireNonNull(destination, "destination must not be null");
Objects.requireNonNull(message, "message must not be null");
Objects.requireNonNull(options, "options must not be null");
long startedAt = nanoTime.getAsLong();
DestinationProfile profile;
MessageEnvelope<EncodedMessage> encoded;
try {
profile = destinations.require(destination.name());
requireSupportedOptions(profile, options);
if (!access.mayPublish(destination.name())) {
// Before encoding: an unauthorized publish must not serialise the payload, because the
// encoded bytes are what a claim-check or a log would then be holding.
return rejected(
"PUBLISH_FORBIDDEN",
"this application may not publish to '" + destination.name().value() + '\'',
startedAt);
}
encoded = encode(message);
} catch (RuntimeException beforeTheWire) {
// Nothing left this process, so the outcome is definite. Reporting it as ambiguous would send
// the caller into reconciliation for a message no broker ever saw.
return rejected("PUBLISH_PREPARATION_FAILED", sanitized(beforeTheWire), startedAt);
}
admission.admit(destination.name().value(), encoded.payload().bytes().length);
MessagingRuntimeLease lease = null;
try {
lease = runtimes.acquire(profile.broker());
MessagingRuntimeLease held = lease;
return transport
.publish(new TransportPublishRequest(profile, encoded, options))
.<PublishResult>handle(
(result, failure) -> {
// One release per acquisition, whatever happened. A permit that leaks on the
// failure path is a limiter that shrinks by one per failure until it accepts
// nothing.
held.close();
admission.complete();
if (failure != null) {
// The request was on the wire when this failed, so the broker may hold it.
PublishResult ambiguous = ambiguousResult(sanitized(failure), startedAt);
observe(profile, ambiguous, startedAt);
return ambiguous;
}
observe(profile, result.result(), startedAt);
return result.result();
});
} catch (RuntimeException beforeTheSend) {
if (lease != null) {
lease.close();
}
admission.complete();
return rejected("PUBLISH_RUNTIME_UNAVAILABLE", sanitized(beforeTheSend), startedAt);
}
}
/**
* Refuses options the destination cannot honour, before anything is encoded or sent.
*
* <p>The transports read {@code request.options()} for nothing: the timeout, the confirmation
* requirement, the deduplication request and the broker hints were all accepted and ignored. A
* caller asking for broker-side deduplication got a publish with no deduplication and no error,
* and then skipped the idempotency it would otherwise have written — which is exactly the case
* {@code PublishDeduplication}'s own javadoc says must be a startup failure rather than a silent
* no-op.
*/
private void requireSupportedOptions(DestinationProfile profile, PublishOptions options) {
if (!options.isM1Compatible()) {
// isM1Compatible existed and nothing called it, so an ordinary caller could attach M3 broker
// hints to an M1 publish and have them dropped.
throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException(
"PUBLISH_BROKER_HINTS_UNSUPPORTED",
"broker hints are an M3 surface and this publish path does not forward them; passing"
+ " them here would drop them silently");
}
if (options.deduplication().isPresent()
&& !transport.capabilities(profile.name()).capabilities().deduplicatedPublish()) {
throw new dev.caskeleton.messaging.api.error.MessagingConfigurationException(
"PUBLISH_DEDUPLICATION_UNSUPPORTED",
"destination '"
+ profile.name().value()
+ "' runs on a broker that does not suppress duplicate publishes of a stable id;"
+ " the caller must keep its own idempotency rather than believing this request");
}
}
/** Records one publish against bounded dimensions: broker, destination, operation, outcome. */
private void observe(DestinationProfile profile, PublishResult result, long startedAt) {
observation.recordPublish(
dev.caskeleton.messaging.observation.MessagingTags.of(
profile.broker(),
profile.name().value(),
"publish",
result.completion().name().toLowerCase(java.util.Locale.ROOT)),
elapsedSince(startedAt));
}
private <T> MessageEnvelope<EncodedMessage> encode(MessageEnvelope<T> message) {
MessageCodec codec = codecs.find(message.contentType()).orElseGet(codecs::defaultCodec);
EncodedMessage bytes =
codec.encode(message.messageType(), message.schemaVersion(), message.payload());
return message.withPayload(bytes);
}
private CompletionStage<PublishResult> rejected(String code, String reason, long startedAt) {
return CompletableFuture.completedFuture(
new PublishResult(
PublishCompletion.REJECTED,
PublishEvidence.notTransmitted(),
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
elapsedSince(startedAt),
Optional.of(
new FailureDescriptor(
FailureCategory.CONFIGURATION, code, false, reason, Optional.empty()))));
}
private PublishResult ambiguousResult(String reason, long startedAt) {
return new PublishResult(
PublishCompletion.AMBIGUOUS,
PublishEvidence.ambiguous(),
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
elapsedSince(startedAt),
Optional.of(
new FailureDescriptor(
FailureCategory.AMBIGUOUS,
"PUBLISH_OUTCOME_UNKNOWN",
true,
reason,
Optional.empty())));
}
/**
* A failure's type, never its message.
*
* <p>A driver message can carry a routing key, a payload fragment or a connection string, and a
* {@code FailureDescriptor} is designed to be logged and exported.
*/
private static String sanitized(Throwable failure) {
Throwable cause =
failure instanceof java.util.concurrent.CompletionException && failure.getCause() != null
? failure.getCause()
: failure;
return cause.getClass().getSimpleName();
}
private Duration elapsedSince(long startedAt) {
return Duration.ofNanos(Math.max(0, nanoTime.getAsLong() - startedAt));
}
}
@@ -0,0 +1,62 @@
package dev.caskeleton.messaging.runtime;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import dev.caskeleton.messaging.policy.DestinationProfile;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
/**
* The closed set of destinations this application may publish to.
*
* <p>Nothing resolved a logical destination to a profile before this: the brokers took an
* already-resolved {@code DestinationProfile} and the publisher that would have produced one did
* not exist. A registry rather than a lookup with a fallback, because a destination nobody declared
* has no physical name, no ordering guarantee and no payload bound — publishing to it would mean
* inventing all three at the call site.
*/
public final class DestinationProfileRegistry {
private final Map<DestinationName, DestinationProfile> profiles;
private DestinationProfileRegistry(Map<DestinationName, DestinationProfile> profiles) {
this.profiles = Map.copyOf(profiles);
}
/** A registry over the given profiles. */
public static DestinationProfileRegistry of(Map<DestinationName, DestinationProfile> profiles) {
return new DestinationProfileRegistry(
new LinkedHashMap<>(Objects.requireNonNull(profiles, "profiles must not be null")));
}
/** An empty registry: every publish is refused until a destination is declared. */
public static DestinationProfileRegistry empty() {
return new DestinationProfileRegistry(Map.of());
}
/**
* The profile for a destination.
*
* @throws MessagingConfigurationException naming the destination, because an unknown destination
* is a configuration mistake and not something to guess a default for
*/
public DestinationProfile require(DestinationName destination) {
Objects.requireNonNull(destination, "destination must not be null");
DestinationProfile profile = profiles.get(destination);
if (profile == null) {
throw new MessagingConfigurationException(
"DESTINATION_NOT_REGISTERED",
"destination '"
+ destination.value()
+ "' has no registered profile; publishing to it would invent its physical name,"
+ " ordering guarantee and payload bound at the call site");
}
return profile;
}
/** How many destinations are declared. */
public int size() {
return profiles.size();
}
}
@@ -0,0 +1,209 @@
package dev.caskeleton.messaging.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.messaging.api.ContentType;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.MessageId;
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.DeliveryMetadata;
import dev.caskeleton.messaging.api.delivery.HandleResult;
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.schema.EncodedMessage;
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.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* One handler 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.
*/
class DefaultDeliveryProcessorTest {
private final RecordingSettlement settlement = new RecordingSettlement();
@Test
@DisplayName("success acknowledges once")
void successAcknowledgesOnce() {
process(envelope -> new HandleResult.Success(), confirmedDeadLetters());
assertThat(settlement.calls()).containsExactly("acknowledge");
}
@Test
@DisplayName("retry requeues with the configured delay")
void retryRequeues() {
process(envelope -> new HandleResult.Retry(failure()), confirmedDeadLetters());
assertThat(settlement.calls()).containsExactly("requeue");
}
@Test
@DisplayName("a handler that throws is retried, not discarded")
void aThrowingHandlerIsRetried() {
process(
envelope -> {
throw new IllegalStateException("a bug in the projection");
},
confirmedDeadLetters());
assertThat(settlement.calls())
.as("treating an exception as undeliverable drops a day of traffic over a transient bug")
.containsExactly("requeue");
}
@Test
@DisplayName("a dead letter is published before the source is acknowledged")
void aDeadLetterIsPublishedBeforeAcknowledgement() {
List<String> order = new ArrayList<>();
DefaultDeliveryProcessor.DeadLetterPublisher publisher =
(envelope, failure) -> {
order.add("dead-letter published");
return CompletableFuture.completedFuture(PublishCompletion.CONFIRMED);
};
settlement.recordInto(order);
process(envelope -> new HandleResult.DeadLetter(failure()), publisher);
assertThat(order).containsExactly("dead-letter published", "acknowledge");
}
@Test
@DisplayName("an unconfirmed dead letter requeues rather than acknowledging")
void anUnconfirmedDeadLetterRequeues() {
process(
envelope -> new HandleResult.DeadLetter(failure()),
(envelope, failure) -> CompletableFuture.completedFuture(PublishCompletion.AMBIGUOUS));
assertThat(settlement.calls())
.as("acknowledging loses the message outright; a duplicate is the recoverable half")
.containsExactly("requeue");
}
@Test
@DisplayName("a rejected message is discarded")
void aRejectedMessageIsDiscarded() {
process(envelope -> new HandleResult.Reject(failure()), confirmedDeadLetters());
assertThat(settlement.calls()).containsExactly("discard");
}
@Test
@DisplayName("a handler returning nothing is retried")
void aHandlerReturningNothingIsRetried() {
process(envelope -> null, confirmedDeadLetters());
assertThat(settlement.calls()).containsExactly("requeue");
}
private void process(
java.util.function.Function<MessageEnvelope<EncodedMessage>, HandleResult> handler,
DefaultDeliveryProcessor.DeadLetterPublisher deadLetters) {
new DefaultDeliveryProcessor(handler, deadLetters, Duration.ofSeconds(5))
.process(new TransportDelivery(envelope(), metadata(), settlement))
.toCompletableFuture()
.join();
}
private static DefaultDeliveryProcessor.DeadLetterPublisher confirmedDeadLetters() {
return (envelope, failure) -> CompletableFuture.completedFuture(PublishCompletion.CONFIRMED);
}
private static FailureDescriptor failure() {
return new FailureDescriptor(
FailureCategory.PERMANENT_BUSINESS,
"UNPROCESSABLE",
false,
"cannot be applied",
Optional.empty());
}
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"));
}
private static MessageEnvelope<EncodedMessage> envelope() {
return new MessageEnvelope<>(
MessageId.newId(),
new MessageType("order.created"),
new SchemaVersion(1),
Instant.parse("2026-08-14T00:00:00Z"),
Optional.empty(),
new ProducerId("orders"),
Optional.empty(),
Optional.empty(),
ContentType.JSON,
Optional.empty(),
Optional.empty(),
Optional.empty(),
TraceContext.none(),
MessageHeaders.empty(),
new EncodedMessage(
"{}".getBytes(StandardCharsets.UTF_8), ContentType.JSON, Optional.empty()));
}
/** Records which terminal call the processor made, and in what order. */
private static final class RecordingSettlement implements TransportSettlement {
private final List<String> calls = new ArrayList<>();
private List<String> shared;
private void recordInto(List<String> order) {
this.shared = order;
}
@Override
public CompletionStage<SettlementResult> acknowledge() {
return record("acknowledge");
}
@Override
public CompletionStage<SettlementResult> requeue(Duration delay) {
return record("requeue");
}
@Override
public CompletionStage<SettlementResult> discard() {
return record("discard");
}
private CompletionStage<SettlementResult> record(String call) {
calls.add(call);
if (shared != null) {
shared.add(call);
}
return CompletableFuture.completedFuture(SettlementResult.settled());
}
private List<String> calls() {
return calls;
}
}
}
@@ -0,0 +1,469 @@
package dev.caskeleton.messaging.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.ContentType;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.MessageId;
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.destination.DestinationCapabilities;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.destination.MessageDestination;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import dev.caskeleton.messaging.api.header.MessageHeaders;
import dev.caskeleton.messaging.api.publish.ConfirmationLevel;
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.InFlightLimiter;
import dev.caskeleton.messaging.policy.MessagingAdmissionController;
import dev.caskeleton.messaging.policy.PayloadLimitGuard;
import dev.caskeleton.messaging.policy.PayloadPolicy;
import dev.caskeleton.messaging.schema.EncodedMessage;
import dev.caskeleton.messaging.schema.MessageCodec;
import dev.caskeleton.messaging.schema.MessageCodecRegistry;
import dev.caskeleton.messaging.security.DestinationAccessPolicy;
import dev.caskeleton.messaging.transport.MessagingRuntime;
import dev.caskeleton.messaging.transport.MessagingRuntimeLease;
import dev.caskeleton.messaging.transport.MessagingRuntimeRegistry;
import dev.caskeleton.messaging.transport.MessagingTransport;
import dev.caskeleton.messaging.transport.TransportConsumerRegistration;
import dev.caskeleton.messaging.transport.TransportConsumerSpec;
import dev.caskeleton.messaging.transport.TransportPublishRequest;
import dev.caskeleton.messaging.transport.TransportPublishResult;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* The publish path, end to end, without an application-supplied publisher.
*
* <p>There was no implementation of {@code MessagePublisher} anywhere in the new platform, so the
* admission controller, the access policy and the runtime registry were beans that no publish ever
* consulted. These tests run the real pipeline against a fake transport.
*/
class DefaultMessagePublisherTest {
private static final DestinationName ORDERS = new DestinationName("order-events");
private final RecordingTransport transport = new RecordingTransport();
private final MessagingAdmissionController admission =
new MessagingAdmissionController(
new PayloadLimitGuard(PayloadPolicy.defaults()),
new InFlightLimiter(4, Duration.ofSeconds(1)));
@Test
@DisplayName("a publish goes through resolution, encoding, admission, lease and transport")
void aPublishRunsTheWholePipeline() {
PublishResult result =
publisher(allowOrders())
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
PublishOptions.defaults())
.toCompletableFuture()
.join();
assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED);
assertThat(transport.published()).isEqualTo(1);
assertThat(admission.inFlight())
.as("a permit that leaks per publish is a limiter that stops accepting after four")
.isZero();
}
@Test
@DisplayName("an unregistered destination is rejected before anything is encoded")
void anUnregisteredDestinationIsRejected() {
DefaultMessagePublisher publisher =
new DefaultMessagePublisher(
DestinationProfileRegistry.empty(),
allowOrders(),
new SingleCodecRegistry(),
admission,
new FixedRuntimeRegistry(transport),
transport);
PublishResult result =
publisher
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
PublishOptions.defaults())
.toCompletableFuture()
.join();
assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED);
assertThat(transport.published()).isZero();
}
@Test
@DisplayName("a forbidden destination is rejected before the payload is encoded")
void aForbiddenDestinationNeverEncodes() {
SingleCodecRegistry codecs = new SingleCodecRegistry();
DefaultMessagePublisher publisher =
new DefaultMessagePublisher(
registry(),
DestinationAccessPolicy.denyAll(),
codecs,
admission,
new FixedRuntimeRegistry(transport),
transport);
PublishResult result =
publisher
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
PublishOptions.defaults())
.toCompletableFuture()
.join();
assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED);
assertThat(codecs.encodes())
.as("the encoded bytes are what a claim check or a log would then be holding")
.isZero();
assertThat(admission.inFlight()).isZero();
}
@Test
@DisplayName("a transport failure is ambiguous, not rejected")
void aTransportFailureIsAmbiguous() {
transport.failWith(new IllegalStateException("connection reset"));
PublishResult result =
publisher(allowOrders())
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
PublishOptions.defaults())
.toCompletableFuture()
.join();
assertThat(result.completion())
.as("the request was on the wire, so the broker may hold it")
.isEqualTo(PublishCompletion.AMBIGUOUS);
assertThat(result.failure().orElseThrow().sanitizedMessage())
.as("a driver message can carry a routing key or a payload fragment")
.isEqualTo("IllegalStateException");
assertThat(admission.inFlight()).isZero();
}
@Test
@DisplayName("an unavailable runtime releases the permit it took")
void anUnavailableRuntimeReleasesThePermit() {
DefaultMessagePublisher publisher =
new DefaultMessagePublisher(
registry(),
allowOrders(),
new SingleCodecRegistry(),
admission,
new FailingRuntimeRegistry(),
transport);
PublishResult result =
publisher
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
PublishOptions.defaults())
.toCompletableFuture()
.join();
assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED);
assertThat(admission.inFlight()).isZero();
}
@Test
@DisplayName("an unregistered destination names itself")
void anUnregisteredDestinationNamesItself() {
assertThatThrownBy(() -> DestinationProfileRegistry.empty().require(ORDERS))
.isInstanceOf(MessagingConfigurationException.class)
.hasMessageContaining("order-events");
}
@Test
@DisplayName("every publish outcome reaches the observation")
void everyPublishOutcomeIsObserved() {
java.util.List<String> outcomes = new java.util.ArrayList<>();
DefaultMessagePublisher publisher =
new DefaultMessagePublisher(
registry(),
allowOrders(),
new SingleCodecRegistry(),
admission,
new FixedRuntimeRegistry(transport),
transport,
System::nanoTime,
new dev.caskeleton.messaging.observation.MessagingObservation() {
@Override
public void recordPublish(
dev.caskeleton.messaging.observation.MessagingTags tags, Duration elapsed) {
outcomes.add(tags.asMap().get("outcome"));
}
@Override
public void recordDelivery(
dev.caskeleton.messaging.observation.MessagingTags tags,
Duration elapsed,
int attempt) {}
@Override
public void recordSettlement(
dev.caskeleton.messaging.observation.MessagingTags tags) {}
@Override
public void recordBacklog(
dev.caskeleton.messaging.observation.MessagingTags tags, long messages) {}
@Override
public void recordDiagnostics(
dev.caskeleton.messaging.observation.MessagingTags tags,
Map<String, String> diagnostics) {}
});
publisher
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
PublishOptions.defaults())
.toCompletableFuture()
.join();
assertThat(outcomes)
.as("the observation bean existed and no publish path ever called it")
.containsExactly("confirmed");
}
@Test
@DisplayName("a deduplication request a broker cannot honour is refused")
void anUnsupportedDeduplicationRequestIsRefused() {
PublishResult result =
publisher(allowOrders())
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
new PublishOptions(
java.time.Duration.ofSeconds(5),
dev.caskeleton.messaging.api.destination.ConfirmationRequirement
.REPLICATION_OR_PERSISTENCE_ACK,
java.util.Optional.of(
new dev.caskeleton.messaging.api.publish.PublishDeduplication(
"order-1", java.time.Duration.ofMinutes(5))),
Map.of()))
.toCompletableFuture()
.join();
assertThat(result.completion())
.as("accepting it silently is how a caller skips the idempotency it would have written")
.isEqualTo(PublishCompletion.REJECTED);
assertThat(transport.published()).isZero();
}
@Test
@DisplayName("M3 broker hints are refused on the M1 path")
void brokerHintsAreRefused() {
PublishResult result =
publisher(allowOrders())
.publish(
new MessageDestination<>(ORDERS, new MessageType("order.created"), String.class),
envelope(),
new PublishOptions(
java.time.Duration.ofSeconds(5),
dev.caskeleton.messaging.api.destination.ConfirmationRequirement
.REPLICATION_OR_PERSISTENCE_ACK,
java.util.Optional.empty(),
Map.of("linger.ms", "50")))
.toCompletableFuture()
.join();
assertThat(result.completion())
.as("isM1Compatible existed and nothing ever called it")
.isEqualTo(PublishCompletion.REJECTED);
}
private static DestinationAccessPolicy allowOrders() {
return new DestinationAccessPolicy(
java.util.Set.of(ORDERS), java.util.Set.of(), java.util.Set.of());
}
private DefaultMessagePublisher publisher(DestinationAccessPolicy access) {
return new DefaultMessagePublisher(
registry(),
access,
new SingleCodecRegistry(),
admission,
new FixedRuntimeRegistry(transport),
transport);
}
private static DestinationProfileRegistry registry() {
return DestinationProfileRegistry.of(Map.of(ORDERS, RuntimeFixtures.profile(ORDERS)));
}
private static MessageEnvelope<String> envelope() {
return new MessageEnvelope<>(
MessageId.newId(),
new MessageType("order.created"),
new SchemaVersion(1),
Instant.parse("2026-08-14T00:00:00Z"),
Optional.empty(),
new ProducerId("orders"),
Optional.empty(),
Optional.empty(),
ContentType.JSON,
Optional.empty(),
Optional.empty(),
Optional.empty(),
TraceContext.none(),
MessageHeaders.empty(),
"{\"orderId\":\"o-1\"}");
}
/** A codec that counts how often it was asked to encode. */
private static final class SingleCodecRegistry implements MessageCodecRegistry {
private final AtomicInteger encodes = new AtomicInteger();
@Override
public Optional<MessageCodec> find(ContentType contentType) {
return Optional.of(codec());
}
@Override
public MessageCodec defaultCodec() {
return codec();
}
private MessageCodec codec() {
return new MessageCodec() {
@Override
public EncodedMessage encode(MessageType type, SchemaVersion version, Object payload) {
encodes.incrementAndGet();
return new EncodedMessage(
String.valueOf(payload).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));
}
@Override
public ContentType contentType() {
return ContentType.JSON;
}
};
}
private int encodes() {
return encodes.get();
}
}
/** A transport that records what reached it. */
private static final class RecordingTransport implements MessagingTransport {
private final AtomicInteger published = new AtomicInteger();
private RuntimeException failure;
private void failWith(RuntimeException failure) {
this.failure = failure;
}
@Override
public CompletionStage<TransportPublishResult> publish(TransportPublishRequest request) {
if (failure != null) {
return CompletableFuture.failedFuture(failure);
}
published.incrementAndGet();
return CompletableFuture.completedFuture(
new TransportPublishResult(
new PublishResult(
PublishCompletion.CONFIRMED,
PublishEvidence.confirmed(ConfirmationLevel.BROKER_ACK),
RoutingOutcome.ROUTED,
Optional.empty(),
1,
Duration.ZERO,
Optional.empty())));
}
@Override
public TransportConsumerRegistration register(TransportConsumerSpec spec) {
throw new UnsupportedOperationException("not used by these tests");
}
@Override
public DestinationCapabilities capabilities(DestinationName destination) {
throw new UnsupportedOperationException("not used by these tests");
}
@Override
public String brokerName() {
return "fake";
}
@Override
public long generation() {
return 1;
}
@Override
public void close() {}
private int published() {
return published.get();
}
}
/** A registry with no installed generation, which is what a rotation gap looks like. */
private static final class FailingRuntimeRegistry implements MessagingRuntimeRegistry {
@Override
public void install(MessagingRuntime runtime) {}
@Override
public MessagingRuntimeLease acquire(String brokerName) {
throw new IllegalStateException("no generation installed");
}
}
/** A registry that always hands out a lease on the same transport. */
private record FixedRuntimeRegistry(MessagingTransport transport)
implements MessagingRuntimeRegistry {
@Override
public void install(MessagingRuntime runtime) {}
@Override
public MessagingRuntimeLease acquire(String brokerName) {
return new MessagingRuntimeLease() {
@Override
public MessagingRuntime runtime() {
throw new UnsupportedOperationException("not used by these tests");
}
@Override
public void close() {}
};
}
}
}
@@ -0,0 +1,44 @@
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.ConsumerPolicy;
import dev.caskeleton.messaging.policy.DeadLetterPolicy;
import dev.caskeleton.messaging.policy.DestinationProfile;
import dev.caskeleton.messaging.policy.PayloadPolicy;
import dev.caskeleton.messaging.policy.PhysicalDestination;
import dev.caskeleton.messaging.policy.ProducerPolicy;
import dev.caskeleton.messaging.schema.SchemaCompatibility;
import java.util.Set;
/** One registered destination, so the pipeline has something real to resolve. */
final class RuntimeFixtures {
private RuntimeFixtures() {}
static DestinationProfile profile(DestinationName name) {
return new DestinationProfile(
name,
"fake",
dev.caskeleton.messaging.api.destination.DestinationKind.EVENT_STREAM,
PhysicalDestination.kafkaTopic("order.events.v1"),
new dev.caskeleton.messaging.policy.SchemaPolicy(
ContentType.JSON,
SchemaCompatibility.BACKWARD_TRANSITIVE,
Set.of(new MessageType("order.created"))),
dev.caskeleton.messaging.api.delivery.DeliveryGuarantee.AT_LEAST_ONCE,
dev.caskeleton.messaging.api.delivery.OrderingScope.NONE,
dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED,
ProducerPolicy.defaults(),
ConsumerPolicy.defaults("order-projection"),
dev.caskeleton.messaging.policy.RetryPolicy.none(),
DeadLetterPolicy.to(new DestinationName("order-events-dlq")),
PayloadPolicy.defaults(),
CapabilityTier.M1,
false,
false,
false);
}
}