feat(messaging): 브로커 중립 메시징 플랫폼 24개 leaf 추가

messaging-superpowers-package 설계서/계획서 기반 구현.
registry를 19 → 43 leaf로 확장하고 src/messaging 아래 24개 leaf를 등록.

- core-api: M1 publish/consume + M2 batch·delayed·pause-resume
- policy/transport-spi: 재시도 결정, DLQ orchestration, admission control, lifecycle
- kafka·rabbit(Stable): contiguous commit, confirm/return 상관, 배치, 보안 설정
- pulsar·nats(Experimental): 기본 비활성, live 인증 없음을 코드로 기록
- outbox/inbox/claim-check: 트랜잭션 결합, lease, 무결성 검증
- admin: plan → approve → execute를 타입으로 강제
- 문서 9종, infra compose 7종, JMH 벤치마크 3종

검증: 아키텍처 게이트 3종 통과, 24개 leaf 전부 check 통과,
messaging 테스트 604개 통과/0 실패.

미완: 계획서가 요구한 실 브로커 IT 40개 중 7개만 작성.
Rabbit 13 / Outbox 6 / Inbox 4 / NATS·Pulsar·Share 5 / testkit 2 /
starter·admin 3, 그리고 TLS·ACL 2개가 남음.
This commit is contained in:
DongHyeonka
2026-08-14 14:55:38 +09:00
parent 432130fd62
commit e23ed9486e
475 changed files with 39748 additions and 0 deletions
@@ -0,0 +1,18 @@
package dev.caskeleton.messaging.api;
import java.util.Objects;
/**
* Identity of the message that directly caused this one.
*
* <p>Unlike {@link CorrelationId}, which spans a whole workflow, this points at exactly one
* predecessor and forms the causal edge used when reconstructing a flow.
*
* @param value the predecessor message identity
*/
public record CausationId(MessageId value) {
public CausationId {
Objects.requireNonNull(value, "causationId value must not be null");
}
}
@@ -0,0 +1,35 @@
package dev.caskeleton.messaging.api;
import java.util.Locale;
/**
* Media type of an encoded payload, resolved through the codec registry.
*
* @param value the media type, for example {@code application/json}
*/
public record ContentType(String value) {
private static final int MAX_LENGTH = 160;
/** The Stable default codec's content type. */
public static final ContentType JSON = new ContentType("application/json");
/** Avro binary content type. */
public static final ContentType AVRO = new ContentType("application/avro");
/** Protobuf binary content type. */
public static final ContentType PROTOBUF = new ContentType("application/x-protobuf");
/** Opaque bytes, only reachable through the M2 raw codec. */
public static final ContentType OCTET_STREAM = new ContentType("application/octet-stream");
public ContentType {
if (value == null || value.isBlank() || value.length() > MAX_LENGTH) {
throw new IllegalArgumentException("contentType must contain 1 to 160 characters");
}
if (value.indexOf('/') < 0) {
throw new IllegalArgumentException("contentType must be a media type: " + value);
}
value = value.toLowerCase(Locale.ROOT);
}
}
@@ -0,0 +1,17 @@
package dev.caskeleton.messaging.api;
/**
* Workflow-scoped correlation value shared by every message of one business flow.
*
* @param value the correlation value, 1 to 160 characters
*/
public record CorrelationId(String value) {
private static final int MAX_LENGTH = 160;
public CorrelationId {
if (value == null || value.isBlank() || value.length() > MAX_LENGTH) {
throw new IllegalArgumentException("correlationId must contain 1 to 160 characters");
}
}
}
@@ -0,0 +1,146 @@
package dev.caskeleton.messaging.api;
import dev.caskeleton.messaging.api.header.MessageHeaders;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
/**
* The platform's unit of transfer: identity, provenance, routing intent, and payload.
*
* <p>The payload is never null. A null Kafka value is a tombstone, which is a distinct
* broker-native operation with different retention semantics, so generalising it into "an envelope
* with no payload" would silently turn a delete into an event on brokers that have no such concept.
*
* @param <T> the payload type
* @param messageId logical identity, preserved across retry, DLQ, and redrive
* @param messageType stable catalog type
* @param schemaVersion payload schema revision
* @param producedAt instant the platform created this envelope
* @param occurredAt instant the business fact occurred; required for events
* @param producer logical producing service
* @param correlationId workflow correlation
* @param causationId directly causing message
* @param contentType codec media type
* @param partitionKey distribution key
* @param orderingKey ordering key
* @param tenantContext bounded tenant identity
* @param traceContext trace propagation values
* @param headers bounded application headers
* @param payload the non-null payload
*/
public record MessageEnvelope<T>(
MessageId messageId,
MessageType messageType,
SchemaVersion schemaVersion,
Instant producedAt,
Optional<Instant> occurredAt,
ProducerId producer,
Optional<CorrelationId> correlationId,
Optional<CausationId> causationId,
ContentType contentType,
Optional<String> partitionKey,
Optional<String> orderingKey,
Optional<TenantContext> tenantContext,
TraceContext traceContext,
MessageHeaders headers,
T payload) {
public MessageEnvelope {
Objects.requireNonNull(messageId, "messageId must not be null");
Objects.requireNonNull(messageType, "messageType must not be null");
Objects.requireNonNull(schemaVersion, "schemaVersion must not be null");
Objects.requireNonNull(producedAt, "producedAt must not be null");
Objects.requireNonNull(occurredAt, "occurredAt must not be null");
Objects.requireNonNull(producer, "producer must not be null");
Objects.requireNonNull(correlationId, "correlationId must not be null");
Objects.requireNonNull(causationId, "causationId must not be null");
Objects.requireNonNull(contentType, "contentType must not be null");
Objects.requireNonNull(partitionKey, "partitionKey must not be null");
Objects.requireNonNull(orderingKey, "orderingKey must not be null");
Objects.requireNonNull(tenantContext, "tenantContext must not be null");
Objects.requireNonNull(traceContext, "traceContext must not be null");
Objects.requireNonNull(headers, "headers must not be null");
Objects.requireNonNull(payload, "payload must not be null");
}
/**
* Returns a copy of this envelope carrying a different payload representation.
*
* <p>Encoding, decoding, Claim Check offloading, and DLQ forwarding all need this, and every one
* of them must keep {@link #messageId()} intact — which is exactly what this method guarantees by
* construction.
*
* @param <R> the replacement payload type
* @param replacement the new payload
* @return an envelope with identical identity and metadata
*/
public <R> MessageEnvelope<R> withPayload(R replacement) {
return new MessageEnvelope<>(
messageId,
messageType,
schemaVersion,
producedAt,
occurredAt,
producer,
correlationId,
causationId,
contentType,
partitionKey,
orderingKey,
tenantContext,
traceContext,
headers,
replacement);
}
/**
* Returns a copy of this envelope carrying a different content type.
*
* @param replacement the new content type
* @return an envelope with identical identity and payload
*/
public MessageEnvelope<T> withContentType(ContentType replacement) {
return new MessageEnvelope<>(
messageId,
messageType,
schemaVersion,
producedAt,
occurredAt,
producer,
correlationId,
causationId,
Objects.requireNonNull(replacement, "contentType must not be null"),
partitionKey,
orderingKey,
tenantContext,
traceContext,
headers,
payload);
}
/**
* Returns a copy of this envelope carrying replacement headers.
*
* @param replacement the new headers
* @return an envelope with identical identity and payload
*/
public MessageEnvelope<T> withHeaders(MessageHeaders replacement) {
return new MessageEnvelope<>(
messageId,
messageType,
schemaVersion,
producedAt,
occurredAt,
producer,
correlationId,
causationId,
contentType,
partitionKey,
orderingKey,
tenantContext,
traceContext,
Objects.requireNonNull(replacement, "headers must not be null"),
payload);
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.messaging.api;
import java.util.Objects;
import java.util.UUID;
/**
* Logical identity of a message.
*
* <p>This value survives publish retry, broker redelivery, retry destinations, dead lettering, and
* redrive. A new {@code MessageId} is minted only for a genuinely new business fact or command, so
* an Inbox can use it to suppress duplicate side effects.
*
* @param value the UUIDv7 identity
*/
public record MessageId(UUID value) {
public MessageId {
Objects.requireNonNull(value, "messageId value must not be null");
}
/**
* Mints a new logical message identity.
*
* @return a fresh time-ordered identity
*/
public static MessageId newId() {
return new MessageId(UuidV7.next());
}
}
@@ -0,0 +1,20 @@
package dev.caskeleton.messaging.api;
/**
* Stable catalog name of a message, such as {@code order.created}.
*
* <p>Java class names are deliberately not usable as a message type: renaming or repackaging a
* class must never change the wire contract.
*
* @param value the catalog name, 1 to 240 characters
*/
public record MessageType(String value) {
private static final int MAX_LENGTH = 240;
public MessageType {
if (value == null || value.isBlank() || value.length() > MAX_LENGTH) {
throw new IllegalArgumentException("messageType must contain 1 to 240 characters");
}
}
}
@@ -0,0 +1,20 @@
package dev.caskeleton.messaging.api;
/**
* Logical service identity of the component that produced a message.
*
* <p>This is a deployment-independent service name, not a host, pod, or connection identity, so
* that it stays a bounded value safe for metric tags.
*
* @param value the service name, 1 to 120 characters
*/
public record ProducerId(String value) {
private static final int MAX_LENGTH = 120;
public ProducerId {
if (value == null || value.isBlank() || value.length() > MAX_LENGTH) {
throw new IllegalArgumentException("producerId must contain 1 to 120 characters");
}
}
}
@@ -0,0 +1,15 @@
package dev.caskeleton.messaging.api;
/**
* Monotonic schema revision of a {@link MessageType}.
*
* @param value the revision, starting at 1
*/
public record SchemaVersion(int value) {
public SchemaVersion {
if (value < 1) {
throw new IllegalArgumentException("schemaVersion must be positive");
}
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.messaging.api;
import java.util.regex.Pattern;
/**
* Bounded tenant identity carried with a message.
*
* <p>The value is deliberately constrained to a short slug. Tenant identity is one of the few
* envelope fields that observability code is tempted to use as a metric label, and an unbounded
* tenant id turns that into a cardinality explosion.
*
* @param tenantId the tenant slug
*/
public record TenantContext(String tenantId) {
private static final Pattern VALID = Pattern.compile("[a-z0-9][a-z0-9._-]{0,63}");
public TenantContext {
if (tenantId == null || !VALID.matcher(tenantId).matches()) {
throw new IllegalArgumentException(
"tenantId must match [a-z0-9][a-z0-9._-]{0,63}: " + tenantId);
}
}
}
@@ -0,0 +1,44 @@
package dev.caskeleton.messaging.api;
import java.util.Objects;
import java.util.Optional;
/**
* W3C trace propagation values carried with a message.
*
* <p>The platform creates and propagates these; handlers do not set them. Keeping them on the
* envelope rather than only in headers means a trace survives an Outbox round trip through the
* database, where broker headers do not exist yet.
*
* @param traceparent the {@code traceparent} value when a trace is active
* @param tracestate the {@code tracestate} value when present
* @param baggage the {@code baggage} value when present
*/
public record TraceContext(
Optional<String> traceparent, Optional<String> tracestate, Optional<String> baggage) {
public TraceContext {
Objects.requireNonNull(traceparent, "traceparent must not be null");
Objects.requireNonNull(tracestate, "tracestate must not be null");
Objects.requireNonNull(baggage, "baggage must not be null");
}
/**
* Returns a context with no active trace.
*
* @return an empty trace context
*/
public static TraceContext none() {
return new TraceContext(Optional.empty(), Optional.empty(), Optional.empty());
}
/**
* Returns a context carrying only a trace parent.
*
* @param traceparent the {@code traceparent} value
* @return a trace context
*/
public static TraceContext of(String traceparent) {
return new TraceContext(Optional.of(traceparent), Optional.empty(), Optional.empty());
}
}
@@ -0,0 +1,62 @@
package dev.caskeleton.messaging.api;
import java.security.SecureRandom;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;
/**
* Generates RFC 9562 UUIDv7 values.
*
* <p>The platform needs message identifiers that sort by creation time so that outbox scans, DLQ
* listings, and broker partitions stay locality-friendly, while still being globally unique. The 12
* bit {@code rand_a} field is used as a monotonic intra-millisecond counter instead of random bits:
* two calls in the same millisecond are then still strictly ordered, which is what makes "same
* logical message keeps the same id" auditable across a retry.
*/
public final class UuidV7 {
private static final SecureRandom RANDOM = new SecureRandom();
/** Packs the 48-bit millisecond timestamp in the high bits and the 12-bit counter in the low. */
private static final AtomicLong STATE = new AtomicLong();
private static final long COUNTER_BITS = 12L;
private static final long COUNTER_MASK = 0xFFFL;
private static final long VERSION_7 = 0x7L;
private static final long VARIANT_RFC9562 = 0x8000_0000_0000_0000L;
private static final long RANDOM_B_MASK = 0x3FFF_FFFF_FFFF_FFFFL;
private UuidV7() {}
/**
* Returns the next monotonically increasing UUIDv7.
*
* @return a version 7, variant 2 UUID
*/
public static UUID next() {
long state = STATE.updateAndGet(UuidV7::advance);
long timestamp = state >>> COUNTER_BITS;
long counter = state & COUNTER_MASK;
long mostSignificantBits = (timestamp << 16) | (VERSION_7 << COUNTER_BITS) | counter;
long leastSignificantBits = (RANDOM.nextLong() & RANDOM_B_MASK) | VARIANT_RFC9562;
return new UUID(mostSignificantBits, leastSignificantBits);
}
/**
* Advances the packed state.
*
* <p>When the clock moved forward the counter restarts at zero. Otherwise the packed value is
* simply incremented: that bumps the counter and, once the 12-bit counter overflows, carries into
* the timestamp field. A backwards clock step therefore never produces a duplicate or a
* descending id, it only borrows from the future.
*/
private static long advance(long previous) {
long now = System.currentTimeMillis();
long previousTimestamp = previous >>> COUNTER_BITS;
if (now > previousTimestamp) {
return now << COUNTER_BITS;
}
return previous + 1;
}
}
@@ -0,0 +1,46 @@
package dev.caskeleton.messaging.api.delivery;
import dev.caskeleton.messaging.api.destination.DestinationName;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
/**
* Batch-wide facts about one delivered batch.
*
* <p>{@code orderingUnit} is what makes a batch safe to hand to an ordered destination. A batch
* drawn from two partitions cannot be settled or retried as a unit without reordering one of them,
* so an ordered destination requires the batch to name exactly one ordering unit and the runtime
* rejects a batch that spans more.
*
* @param destination the logical destination
* @param size the number of deliveries in the batch
* @param orderingUnit the single partition or queue the batch was drawn from, when it has one
* @param settlableAsBatch whether the broker can settle the whole batch in one operation
* @param receivedAt when the consumer assembled the batch
*/
public record BatchDeliveryMetadata(
DestinationName destination,
int size,
Optional<String> orderingUnit,
boolean settlableAsBatch,
Instant receivedAt) {
public BatchDeliveryMetadata {
Objects.requireNonNull(destination, "destination must not be null");
Objects.requireNonNull(orderingUnit, "orderingUnit must not be null");
Objects.requireNonNull(receivedAt, "receivedAt must not be null");
if (size < 1) {
throw new IllegalArgumentException("a delivered batch has at least one delivery");
}
}
/**
* Reports whether this batch may be handed to a destination with strict ordering.
*
* @return true when the batch came from exactly one ordering unit
*/
public boolean isSafeForOrderedDestination() {
return orderingUnit.isPresent();
}
}
@@ -0,0 +1,29 @@
package dev.caskeleton.messaging.api.delivery;
import java.util.List;
import java.util.Objects;
/**
* A batch of decoded messages handed to a batch handler.
*
* @param <T> the payload type
* @param deliveries the individual deliveries, in broker order
* @param metadata batch-wide facts
*/
public record BatchMessageDelivery<T>(
List<MessageDelivery<T>> deliveries, BatchDeliveryMetadata metadata) {
public BatchMessageDelivery {
Objects.requireNonNull(deliveries, "deliveries must not be null");
Objects.requireNonNull(metadata, "metadata must not be null");
deliveries = List.copyOf(deliveries);
if (deliveries.isEmpty()) {
throw new IllegalArgumentException("a delivered batch is never empty");
}
if (deliveries.size() != metadata.size()) {
throw new IllegalArgumentException(
"metadata size %d does not match %d deliveries"
.formatted(metadata.size(), deliveries.size()));
}
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.messaging.api.delivery;
import java.util.concurrent.CompletionStage;
/**
* The M2 batch consume entry point.
*
* <p>The handler returns one {@link HandleResult} for the whole batch. On a broker that settles
* batches atomically the runtime applies that result once; on a broker that settles per message it
* applies the same result to each delivery. Either way the handler is not asked to reason about
* which settlement mode it is running under.
*
* @param <T> the payload type
*/
public interface BatchMessageHandler<T> {
/**
* Handles one delivered batch.
*
* @param batch the batch to handle
* @return a stage completing with the outcome for the whole batch
*/
CompletionStage<HandleResult> handle(BatchMessageDelivery<T> batch);
}
@@ -0,0 +1,36 @@
package dev.caskeleton.messaging.api.delivery;
import java.time.Instant;
import java.util.Objects;
/**
* Runtime context handed to a handler alongside a delivery.
*
* <p>{@code shutdownRequested} is visible to handlers on purpose: during a graceful drain the
* platform stops creating new retry attempts, and a long-running handler that can wind down early
* shortens the drain instead of being cancelled at the deadline.
*
* @param handlerDeadline the instant after which the handler is considered timed out
* @param shutdownRequested whether the consumer has begun draining
* @param consumerId the stable, low-cardinality consumer identity
*/
public record DeliveryContext(
Instant handlerDeadline, boolean shutdownRequested, String consumerId) {
public DeliveryContext {
Objects.requireNonNull(handlerDeadline, "handlerDeadline must not be null");
if (consumerId == null || consumerId.isBlank()) {
throw new IllegalArgumentException("consumerId must not be blank");
}
}
/**
* Reports whether the handler deadline has passed.
*
* @param now the current instant
* @return true when the deadline has elapsed
*/
public boolean isExpired(Instant now) {
return !now.isBefore(handlerDeadline);
}
}
@@ -0,0 +1,18 @@
package dev.caskeleton.messaging.api.delivery;
/**
* Broker-level delivery guarantee offered by the common contract.
*
* <p>There is deliberately no {@code EXACTLY_ONCE} constant. No broker delivers exactly-once across
* an external side effect; what real systems provide is at-least-once delivery combined with an
* idempotent or transactional consumer. Naming a guarantee the platform cannot honour would push
* that responsibility out of sight, so the enum stops where the evidence stops.
*/
public enum DeliveryGuarantee {
/** Delivery may be lost; duplicate suppression is preferred over durability. */
AT_MOST_ONCE,
/** Redelivery is possible; durability is preferred over duplicate suppression. */
AT_LEAST_ONCE
}
@@ -0,0 +1,46 @@
package dev.caskeleton.messaging.api.delivery;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.publish.BrokerPosition;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
/**
* Transport-side facts about one delivery attempt.
*
* <p>The first delivery is attempt one, not zero. Off-by-one confusion here directly changes how
* many times a poison message is replayed before it is parked, so the counting rule is fixed at the
* contract rather than left to each adapter.
*
* @param destination the logical destination
* @param deliveryAttempt the attempt number, starting at one
* @param redelivered whether the broker flagged this as a redelivery
* @param brokerPosition the broker coordinate when available
* @param partitionOrQueue the ordering unit when available
* @param consumerGroup the consumer group when applicable
* @param receivedAt when the consumer received the delivery
*/
public record DeliveryMetadata(
DestinationName destination,
int deliveryAttempt,
boolean redelivered,
Optional<BrokerPosition> brokerPosition,
Optional<String> partitionOrQueue,
Optional<String> consumerGroup,
Instant receivedAt) {
public DeliveryMetadata {
Objects.requireNonNull(destination, "destination must not be null");
Objects.requireNonNull(brokerPosition, "brokerPosition must not be null");
Objects.requireNonNull(partitionOrQueue, "partitionOrQueue must not be null");
Objects.requireNonNull(consumerGroup, "consumerGroup must not be null");
Objects.requireNonNull(receivedAt, "receivedAt must not be null");
if (deliveryAttempt < 1) {
throw new IllegalArgumentException("deliveryAttempt counts the first delivery as 1");
}
if (deliveryAttempt == 1 && redelivered) {
throw new IllegalArgumentException("the first delivery attempt cannot be a redelivery");
}
}
}
@@ -0,0 +1,14 @@
package dev.caskeleton.messaging.api.delivery;
/** How a handler's external side effect is protected against redelivery. */
public enum ExternalSideEffectGuarantee {
/** Nothing protects the side effect; only valid where replay is harmless. */
NONE,
/** The handler must make the side effect idempotent itself. */
IDEMPOTENCY_REQUIRED,
/** An Inbox row and the side effect commit inside the same database transaction. */
INBOX_TRANSACTIONAL
}
@@ -0,0 +1,60 @@
package dev.caskeleton.messaging.api.delivery;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import java.util.Objects;
/**
* What an M1 handler decided about a delivery.
*
* <p>The handler states an intent; the platform performs the settlement. That split is what keeps
* "acknowledge only after the handler succeeded" a platform invariant rather than something each
* handler has to remember, and it is why no variant here carries a broker acknowledgement handle.
*/
public sealed interface HandleResult
permits HandleResult.Success, HandleResult.Retry, HandleResult.DeadLetter, HandleResult.Reject {
/** Processing succeeded; the platform may settle the source. */
record Success() implements HandleResult {}
/**
* Processing failed in a way that may succeed later.
*
* @param failure the sanitized failure description
*/
record Retry(FailureDescriptor failure) implements HandleResult {
public Retry {
Objects.requireNonNull(failure, "failure must not be null");
}
}
/**
* Processing failed permanently; route to the dead letter destination.
*
* @param failure the sanitized failure description
*/
record DeadLetter(FailureDescriptor failure) implements HandleResult {
public DeadLetter {
Objects.requireNonNull(failure, "failure must not be null");
}
}
/**
* Discard the message without dead lettering.
*
* @param failure the sanitized failure description
*/
record Reject(FailureDescriptor failure) implements HandleResult {
public Reject {
Objects.requireNonNull(failure, "failure must not be null");
}
}
/**
* Returns a successful result.
*
* @return the success variant
*/
static HandleResult success() {
return new Success();
}
}
@@ -0,0 +1,22 @@
package dev.caskeleton.messaging.api.delivery;
import dev.caskeleton.messaging.api.MessageEnvelope;
import java.util.Objects;
/**
* One decoded message handed to a handler.
*
* @param <T> the payload type
* @param message the decoded envelope
* @param metadata transport-side delivery facts
* @param context runtime context for this attempt
*/
public record MessageDelivery<T>(
MessageEnvelope<T> message, DeliveryMetadata metadata, DeliveryContext context) {
public MessageDelivery {
Objects.requireNonNull(message, "message must not be null");
Objects.requireNonNull(metadata, "metadata must not be null");
Objects.requireNonNull(context, "context must not be null");
}
}
@@ -0,0 +1,23 @@
package dev.caskeleton.messaging.api.delivery;
import java.util.concurrent.CompletionStage;
/**
* The M1 typed handler implemented by ordinary business code.
*
* <p>Handlers state an outcome and never touch broker acknowledgement APIs. Duplicate delivery is a
* normal condition, not an error: implementations are expected to be idempotent, or to sit behind
* the Inbox.
*
* @param <T> the payload type
*/
public interface MessageHandler<T> {
/**
* Handles one delivery.
*
* @param delivery the decoded message and its metadata
* @return a stage completing with the handling outcome
*/
CompletionStage<HandleResult> handle(MessageDelivery<T> delivery);
}
@@ -0,0 +1,23 @@
package dev.caskeleton.messaging.api.delivery;
/**
* The real scope inside which message order is preserved.
*
* <p>There is deliberately no {@code GLOBAL} constant. Ordering is a property of a partition, a key
* mapping, or a single consumer — never of a whole destination — and advertising a global scope
* would promise something no partitioned broker can keep.
*/
public enum OrderingScope {
/** No order is promised. */
NONE,
/** Order holds across the destination, which requires a single ordering unit. */
DESTINATION,
/** Order holds inside one broker partition. */
PARTITION,
/** Order holds for one key while its mapping to an ordering unit is stable. */
KEY
}
@@ -0,0 +1,33 @@
package dev.caskeleton.messaging.api.delivery;
import dev.caskeleton.messaging.api.destination.DestinationName;
import java.util.concurrent.CompletionStage;
/**
* The M2 consumer flow-control entry point.
*
* <p>Pausing stops new deliveries; it does not abandon the ones already in flight. A paused
* consumer stays a member of its group and keeps its assignment, which is the point: leaving the
* group to stop consuming would trigger a rebalance and hand the work to another instance that is
* just as overloaded.
*/
public interface PauseResumeController {
/**
* Stops new deliveries for a destination scope.
*
* @param destination the logical destination
* @param scope the partition, queue, or {@code "*"} for every assigned unit
* @return a stage completing once no further deliveries will be dispatched
*/
CompletionStage<Void> pause(DestinationName destination, String scope);
/**
* Resumes deliveries for a destination scope.
*
* @param destination the logical destination
* @param scope the partition, queue, or {@code "*"} for every assigned unit
* @return a stage completing once deliveries may flow again
*/
CompletionStage<Void> resume(DestinationName destination, String scope);
}
@@ -0,0 +1,11 @@
package dev.caskeleton.messaging.api.delivery;
/** How duplicate processing is neutralised once a message has been delivered. */
public enum ProcessingGuarantee {
/** The handler suppresses duplicate effects using the message id or a business key. */
APPLICATION_IDEMPOTENT,
/** Atomicity holds only inside the transaction scope the broker itself defines. */
BROKER_TRANSACTIONAL
}
@@ -0,0 +1,15 @@
package dev.caskeleton.messaging.api.destination;
/** Resolves the capability snapshot for a logical destination. */
public interface CapabilityRegistry {
/**
* Returns the capabilities of a destination.
*
* @param destination the logical destination
* @return the capability snapshot
* @throws dev.caskeleton.messaging.api.error.MessagingConfigurationException when the destination
* is not registered
*/
DestinationCapabilities capabilities(DestinationName destination);
}
@@ -0,0 +1,20 @@
package dev.caskeleton.messaging.api.destination;
/**
* The publish confirmation a destination profile demands.
*
* <p>This is the requested level. What the broker actually supplied is reported separately as a
* confirmation level on the publish evidence, so a profile asking for replication evidence against
* an adapter that can only prove a broker ack fails at startup instead of silently downgrading.
*/
public enum ConfirmationRequirement {
/** No confirmation is required; only valid for at-most-once profiles. */
NONE,
/** The broker must acknowledge receipt. */
BROKER_ACK,
/** The broker must acknowledge replication or persistence. */
REPLICATION_OR_PERSISTENCE_ACK
}
@@ -0,0 +1,26 @@
package dev.caskeleton.messaging.api.destination;
import java.util.Objects;
/**
* A capability snapshot bound to one logical destination.
*
* <p>Capabilities are per destination, not per broker: the same Kafka cluster offers keyed ordering
* on a partitioned topic and none on a share group, and the same RabbitMQ node offers native dead
* lettering only where the queue was declared with one.
*
* @param destination the logical destination
* @param broker the adapter's broker name
* @param capabilities what the adapter can prove for this destination
*/
public record DestinationCapabilities(
DestinationName destination, String broker, MessagingCapabilities capabilities) {
public DestinationCapabilities {
Objects.requireNonNull(destination, "destination must not be null");
Objects.requireNonNull(capabilities, "capabilities must not be null");
if (broker == null || broker.isBlank()) {
throw new IllegalArgumentException("broker must not be blank");
}
}
}
@@ -0,0 +1,32 @@
package dev.caskeleton.messaging.api.destination;
/**
* The interaction pattern a destination implements.
*
* <p>This drives validation rather than transport: an event stream may keep ordering and replay, a
* work queue may not, and a request-reply destination needs a correlation strategy no other kind
* requires.
*/
public enum DestinationKind {
/** Point-to-point command delivered to exactly one logical handler. */
ASYNC_COMMAND,
/** Fact published inside one bounded context. */
DOMAIN_EVENT,
/** Fact published across bounded contexts under a stable schema contract. */
INTEGRATION_EVENT,
/** Competing consumers draining a shared backlog. */
WORK_QUEUE,
/** Fan-out to independent subscribers. */
PUBLISH_SUBSCRIBE,
/** Retained, replayable, partitioned log. */
EVENT_STREAM,
/** Correlated request and reply, available only as an M2 capability. */
REQUEST_REPLY
}
@@ -0,0 +1,24 @@
package dev.caskeleton.messaging.api.destination;
import java.util.regex.Pattern;
/**
* Logical name of a destination.
*
* <p>The pattern excludes {@code :}, {@code /}, and whitespace so that a broker address can never
* be smuggled in as a logical name. {@code topic://orders} has to fail here, otherwise the physical
* mapping owned by the destination profile could be bypassed from application code.
*
* @param value the logical name
*/
public record DestinationName(String value) {
private static final Pattern VALID = Pattern.compile("[a-z0-9][a-z0-9.-]{0,159}");
public DestinationName {
if (value == null || !VALID.matcher(value).matches()) {
throw new IllegalArgumentException(
"destination name must match [a-z0-9][a-z0-9.-]{0,159}: " + value);
}
}
}
@@ -0,0 +1,26 @@
package dev.caskeleton.messaging.api.destination;
import dev.caskeleton.messaging.api.MessageType;
import java.util.Objects;
/**
* The application-facing handle for a destination.
*
* <p>It carries a logical name, the catalog message type, and the payload class — never a topic,
* exchange, queue, or subject. The physical mapping lives in the destination profile, which is what
* lets the same code run against Kafka in production and an in-memory harness in tests.
*
* @param <T> the payload type
* @param name the logical destination name
* @param messageType the catalog message type
* @param payloadType the payload class
*/
public record MessageDestination<T>(
DestinationName name, MessageType messageType, Class<T> payloadType) {
public MessageDestination {
Objects.requireNonNull(name, "destination name must not be null");
Objects.requireNonNull(messageType, "destination messageType must not be null");
Objects.requireNonNull(payloadType, "destination payloadType must not be null");
}
}
@@ -0,0 +1,47 @@
package dev.caskeleton.messaging.api.destination;
/**
* What a broker adapter can actually prove or do.
*
* <p>The common API does not assume every broker supports every feature. When a profile asks for
* something absent here the platform fails loudly — at startup where possible, otherwise with a
* capability exception — rather than quietly degrading, because a silently weakened guarantee is
* indistinguishable from a working one until the incident.
*
* @param brokerAcknowledgement the adapter can prove the broker accepted a publish
* @param replicationOrPersistenceEvidence the adapter can prove replication or persistence
* @param perMessageSettlement individual messages can be settled
* @param batchSettlement batches can be settled as a unit
* @param orderedStream the destination preserves order inside an ordering unit
* @param keyedOrdering order is preserved per key
* @param replay historical messages can be re-read
* @param delayedDelivery delivery can be scheduled for a future instant
* @param brokerTransaction the broker offers a transaction scope
* @param deduplicatedPublish the broker suppresses duplicate publishes of a stable id
* @param nativeDeadLetter the broker provides dead lettering itself
* @param topologyManagement topology can be inspected or created through the adapter
*/
public record MessagingCapabilities(
boolean brokerAcknowledgement,
boolean replicationOrPersistenceEvidence,
boolean perMessageSettlement,
boolean batchSettlement,
boolean orderedStream,
boolean keyedOrdering,
boolean replay,
boolean delayedDelivery,
boolean brokerTransaction,
boolean deduplicatedPublish,
boolean nativeDeadLetter,
boolean topologyManagement) {
/**
* Returns a capability set with nothing enabled.
*
* @return the empty capability set
*/
public static MessagingCapabilities none() {
return new MessagingCapabilities(
false, false, false, false, false, false, false, false, false, false, false, false);
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.messaging.api.error;
/**
* The stable classification a retry engine, DLQ router, and dashboard all agree on.
*
* <p>Categories exist so that retry decisions are made from a declared class of failure rather than
* from exception type matching, which drifts every time a client library is upgraded.
*/
public enum FailureCategory {
/** Broker or network fault expected to clear on its own. */
TRANSIENT_INFRASTRUCTURE,
/** The broker or a downstream applied backpressure or a quota. */
THROTTLED,
/** The handler failed in a way that may succeed on redelivery. */
PROCESSING_TRANSIENT,
/** The business rejected the message; redelivery cannot help. */
PERMANENT_BUSINESS,
/** The message repeatedly destroys its consumer and must be parked. */
POISON_MESSAGE,
/** The payload could not be decoded against its schema. */
DESERIALIZATION,
/** Broker authentication failed. */
AUTHENTICATION,
/** Broker authorization denied the operation. */
AUTHORIZATION,
/** The outcome could not be determined. */
AMBIGUOUS,
/** The platform or destination is misconfigured. */
CONFIGURATION
}
@@ -0,0 +1,80 @@
package dev.caskeleton.messaging.api.error;
import java.util.Objects;
import java.util.Optional;
/**
* A sanitized, transportable description of a failure.
*
* <p>This travels in reserved headers to retry destinations and DLQs, so it deliberately holds no
* payload, no stack trace, no credential, and no actual message key. Stack traces belong in secure
* log storage; a DLQ is read by more people than the log is.
*
* @param category the stable classification
* @param code a stable, machine-readable code
* @param retryable whether automatic retry is permitted
* @param sanitizedMessage a short operator-facing description
* @param exceptionType the originating exception's simple type name, when known
*/
public record FailureDescriptor(
FailureCategory category,
String code,
boolean retryable,
String sanitizedMessage,
Optional<String> exceptionType) {
private static final int MAX_MESSAGE_LENGTH = 512;
private static final int MAX_CODE_LENGTH = 120;
public FailureDescriptor {
Objects.requireNonNull(category, "failure category must not be null");
Objects.requireNonNull(exceptionType, "exceptionType must not be null");
if (code == null || code.isBlank() || code.length() > MAX_CODE_LENGTH) {
throw new IllegalArgumentException("failure code must contain 1 to 120 characters");
}
if (sanitizedMessage == null) {
throw new IllegalArgumentException("sanitizedMessage must not be null");
}
if (sanitizedMessage.length() > MAX_MESSAGE_LENGTH) {
sanitizedMessage = sanitizedMessage.substring(0, MAX_MESSAGE_LENGTH);
}
}
/**
* Builds a descriptor whose retryability follows the category's default.
*
* @param category the classification
* @param code the stable code
* @param sanitizedMessage the operator-facing description
* @return a descriptor
*/
public static FailureDescriptor of(
FailureCategory category, String code, String sanitizedMessage) {
return new FailureDescriptor(
category, code, defaultRetryable(category), sanitizedMessage, Optional.empty());
}
/**
* Reports whether a category is a retry candidate by default.
*
* <p>Deserialization, authentication, authorization, and configuration failures are never retried
* automatically: each of them fails identically on every redelivery, so retrying only multiplies
* the load while the message is still poison.
*
* @param category the classification
* @return true when automatic retry is allowed by default
*/
public static boolean defaultRetryable(FailureCategory category) {
return switch (category) {
case TRANSIENT_INFRASTRUCTURE, THROTTLED, PROCESSING_TRANSIENT -> true;
case PERMANENT_BUSINESS,
POISON_MESSAGE,
DESERIALIZATION,
AUTHENTICATION,
AUTHORIZATION,
AMBIGUOUS,
CONFIGURATION ->
false;
};
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** Broker authentication failed. */
public class MessageAuthenticationException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.AUTHENTICATION;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageAuthenticationException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageAuthenticationException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageAuthenticationException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The broker denied the operation for these credentials. */
public class MessageAuthorizationException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.AUTHORIZATION;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageAuthorizationException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageAuthorizationException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageAuthorizationException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* Admission was refused because the platform is already at its in-flight or buffer ceiling.
*
* <p>Retryable, and deliberately raised rather than absorbed by an unbounded wait. Blocking the
* caller until a slot frees turns producer-side saturation into thread exhaustion in the calling
* application, which is a far worse failure than a fast rejection the caller can shed or retry.
*
* <p>Nothing was transmitted when this is thrown, so the message has no ambiguity: the caller may
* resubmit it under the same {@code messageId} without risking a duplicate.
*/
public class MessageBackpressureException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.TRANSIENT_INFRASTRUCTURE;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageBackpressureException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, true, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageBackpressureException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The broker could not be reached. */
public class MessageBrokerUnavailableException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.TRANSIENT_INFRASTRUCTURE;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageBrokerUnavailableException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, true, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageBrokerUnavailableException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
true,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageBrokerUnavailableException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The consumer runtime failed while handling a delivery. */
public class MessageConsumerException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PROCESSING_TRANSIENT;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageConsumerException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, true, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageConsumerException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
true,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageConsumerException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* Publishing to the dead letter destination failed.
*
* <p>The source message stays unsettled. Acknowledging a source whose DLQ publish failed would
* destroy the only remaining copy.
*/
public class MessageDeadLetterException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.TRANSIENT_INFRASTRUCTURE;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageDeadLetterException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, true, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageDeadLetterException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
true,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageDeadLetterException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* The handler exceeded its timeout.
*
* <p>Whether the handler committed a side effect before the deadline is unknown, so the delivery is
* recorded as possibly duplicated when it is retried.
*/
public class MessageHandlerTimeoutException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PROCESSING_TRANSIENT;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageHandlerTimeoutException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, true, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageHandlerTimeoutException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
true,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageHandlerTimeoutException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** A header was reserved, secret, or exceeded a limit. */
public class MessageHeaderRejectedException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PERMANENT_BUSINESS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageHeaderRejectedException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageHeaderRejectedException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageHeaderRejectedException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* The publish outcome could not be determined.
*
* <p>The broker may hold the message. Republishing is permitted only under the same logical message
* id, so that broker deduplication or a downstream Inbox can collapse the duplicate.
*/
public class MessagePublishAmbiguousException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.AMBIGUOUS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessagePublishAmbiguousException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessagePublishAmbiguousException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessagePublishAmbiguousException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,53 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* The broker definitively refused the publish.
*
* <p>The message is known not to be stored, so abandoning this attempt is safe.
*/
public class MessagePublishRejectedException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PERMANENT_BUSINESS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessagePublishRejectedException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessagePublishRejectedException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessagePublishRejectedException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* The publish deadline expired before a confirmation arrived.
*
* <p>A timeout is not a rejection. The bytes may already be replicated, so this is classified as
* ambiguous rather than failed.
*/
public class MessagePublishTimeoutException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.AMBIGUOUS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessagePublishTimeoutException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessagePublishTimeoutException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessagePublishTimeoutException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** A redrive operation failed. */
public class MessageRedriveException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.TRANSIENT_INFRASTRUCTURE;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageRedriveException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, true, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageRedriveException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
true,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageRedriveException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The retry policy's attempt budget was exhausted. */
public class MessageRetryExhaustedException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PERMANENT_BUSINESS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageRetryExhaustedException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageRetryExhaustedException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageRetryExhaustedException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The broker accepted the publish but could not route it. */
public class MessageRoutingException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PERMANENT_BUSINESS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageRoutingException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageRoutingException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageRoutingException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The payload's schema is incompatible with the registered contract. */
public class MessageSchemaIncompatibleException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.DESERIALIZATION;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageSchemaIncompatibleException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageSchemaIncompatibleException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageSchemaIncompatibleException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The payload could not be encoded or decoded. */
public class MessageSerializationException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.DESERIALIZATION;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageSerializationException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageSerializationException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageSerializationException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** Settlement was refused by the broker. */
public class MessageSettlementException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.TRANSIENT_INFRASTRUCTURE;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageSettlementException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, true, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageSettlementException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
true,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageSettlementException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,53 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* Settlement was sent but not confirmed.
*
* <p>Redelivery is possible. Callers must not treat this as a successful settlement.
*/
public class MessageSettlementUnknownException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.AMBIGUOUS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageSettlementUnknownException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageSettlementUnknownException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageSettlementUnknownException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* The encoded payload exceeds the destination's byte limit.
*
* <p>Payloads above the portability limit are expected to use Claim Check rather than a larger
* broker frame, so this failure points at a design choice and never at a transient fault.
*/
public class MessageTooLargeException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PERMANENT_BUSINESS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageTooLargeException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageTooLargeException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageTooLargeException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The broker topology does not match the declared manifest. */
public class MessageTopologyException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.CONFIGURATION;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageTopologyException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageTopologyException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageTopologyException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/** The envelope failed platform validation before transport. */
public class MessageValidationException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.PERMANENT_BUSINESS;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessageValidationException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessageValidationException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessageValidationException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,56 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* A requested feature is not supported by the destination's adapter.
*
* <p>Thrown instead of quietly degrading. Downgrading replication evidence to a bare ack, or
* ordered delivery to unordered, produces a system that looks healthy right up to the moment the
* guarantee actually mattered.
*/
public class MessagingCapabilityUnavailableException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.CONFIGURATION;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessagingCapabilityUnavailableException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessagingCapabilityUnavailableException(
String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessagingCapabilityUnavailableException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,55 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Optional;
/**
* The platform or a destination profile is misconfigured.
*
* <p>Raised at startup wherever possible. A configuration fault discovered at publish time has
* already cost a request, so the destination profile validator promotes as many of these as it can
* to application startup.
*/
public class MessagingConfigurationException extends MessagingException {
@Serial private static final long serialVersionUID = 1L;
private static final FailureCategory CATEGORY = FailureCategory.CONFIGURATION;
/**
* Creates the exception with a stable code and sanitized message.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
*/
public MessagingConfigurationException(String code, String sanitizedMessage) {
super(new FailureDescriptor(CATEGORY, code, false, sanitizedMessage, Optional.empty()));
}
/**
* Creates the exception with an originating cause.
*
* @param code the stable failure code
* @param sanitizedMessage the operator-facing description
* @param cause the originating throwable
*/
public MessagingConfigurationException(String code, String sanitizedMessage, Throwable cause) {
super(
new FailureDescriptor(
CATEGORY,
code,
false,
sanitizedMessage,
Optional.ofNullable(cause).map(value -> value.getClass().getSimpleName())),
cause);
}
/**
* Creates the exception from an explicit descriptor.
*
* @param failure the sanitized failure description
*/
public MessagingConfigurationException(FailureDescriptor failure) {
super(failure);
}
}
@@ -0,0 +1,66 @@
package dev.caskeleton.messaging.api.error;
import java.io.Serial;
import java.util.Objects;
/**
* Root of the platform's stable exception hierarchy.
*
* <p>Every subclass carries a {@link FailureDescriptor} so that a caller catching the base type can
* still classify and route the failure without matching on exception classes. The message exposed
* here is the sanitized one; nothing on this type carries payload or credentials.
*/
public abstract class MessagingException extends RuntimeException {
@Serial private static final long serialVersionUID = 1L;
private final FailureDescriptor failure;
/**
* Creates an exception from a descriptor.
*
* @param failure the sanitized failure description
*/
protected MessagingException(FailureDescriptor failure) {
super(Objects.requireNonNull(failure, "failure must not be null").sanitizedMessage());
this.failure = failure;
}
/**
* Creates an exception from a descriptor and an originating cause.
*
* @param failure the sanitized failure description
* @param cause the originating throwable
*/
protected MessagingException(FailureDescriptor failure, Throwable cause) {
super(Objects.requireNonNull(failure, "failure must not be null").sanitizedMessage(), cause);
this.failure = failure;
}
/**
* Returns the sanitized failure description.
*
* @return the descriptor
*/
public FailureDescriptor failure() {
return failure;
}
/**
* Returns the stable classification.
*
* @return the failure category
*/
public FailureCategory category() {
return failure.category();
}
/**
* Reports whether automatic retry is permitted.
*
* @return true when retryable
*/
public boolean retryable() {
return failure.retryable();
}
}
@@ -0,0 +1,36 @@
package dev.caskeleton.messaging.api.header;
import java.nio.charset.StandardCharsets;
/**
* Name of a single message header.
*
* <p>Header names are compared case-insensitively because brokers disagree on case handling: AMQP
* preserves it, HTTP-style bindings fold it. Storing the name verbatim but normalising for lookup
* keeps a forged {@code MSG.ID} from slipping past the reserved-name check.
*
* @param value the header name as written by the caller
*/
public record HeaderName(String value) {
private static final int MAX_BYTES = 128;
public HeaderName {
if (value == null || value.isBlank()) {
throw new IllegalArgumentException("header name must not be blank");
}
int bytes = value.getBytes(StandardCharsets.UTF_8).length;
if (bytes > MAX_BYTES) {
throw new IllegalArgumentException("header name exceeds 128 bytes: " + bytes);
}
}
/**
* Returns the lowercase form used for reserved and secret name matching.
*
* @return the normalised name
*/
public String normalized() {
return value.toLowerCase(java.util.Locale.ROOT);
}
}
@@ -0,0 +1,23 @@
package dev.caskeleton.messaging.api.header;
import java.nio.charset.StandardCharsets;
/**
* Value of a single message header.
*
* @param value the header value, at most 4096 UTF-8 bytes
*/
public record HeaderValue(String value) {
private static final int MAX_BYTES = 4096;
public HeaderValue {
if (value == null) {
throw new IllegalArgumentException("header value must not be null");
}
int bytes = value.getBytes(StandardCharsets.UTF_8).length;
if (bytes > MAX_BYTES) {
throw new IllegalArgumentException("header value exceeds 4096 bytes: " + bytes);
}
}
}
@@ -0,0 +1,164 @@
package dev.caskeleton.messaging.api.header;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* An immutable, bounded header map.
*
* <p>Two separate factories exist on purpose. {@link #application(Map)} is what business code calls
* and it refuses both reserved and secret names; {@link #platform(Map)} is what adapters call when
* rehydrating an envelope off the wire and it may write reserved names. Secret names are refused in
* both: a credential that reaches a header ends up in broker storage, DLQ dumps, and operator
* tooling, and no downstream redaction can undo that.
*/
public final class MessageHeaders {
private static final int MAX_COUNT = 64;
private static final int MAX_TOTAL_BYTES = 32_768;
private static final Set<String> SECRET_NAMES =
Set.of(
"authorization",
"proxy-authorization",
"cookie",
"set-cookie",
"access_token",
"refresh_token",
"api_key",
"password",
"client_secret");
private static final MessageHeaders EMPTY = new MessageHeaders(Map.of());
private final Map<HeaderName, HeaderValue> values;
private MessageHeaders(Map<HeaderName, HeaderValue> values) {
this.values = values;
}
/**
* Returns the empty header map.
*
* @return headers with no entries
*/
public static MessageHeaders empty() {
return EMPTY;
}
/**
* Validates and copies application-supplied headers.
*
* @param input the caller's headers
* @return an immutable copy
* @throws IllegalArgumentException when a reserved or secret name is present, or a limit is
* exceeded
*/
public static MessageHeaders application(Map<HeaderName, HeaderValue> input) {
return validateAndCopy(input, false);
}
/**
* Validates and copies platform-supplied headers, allowing reserved names.
*
* @param input the platform's headers
* @return an immutable copy
* @throws IllegalArgumentException when a secret name is present or a limit is exceeded
*/
public static MessageHeaders platform(Map<HeaderName, HeaderValue> input) {
return validateAndCopy(input, true);
}
private static MessageHeaders validateAndCopy(
Map<HeaderName, HeaderValue> input, boolean reservedAllowed) {
if (input == null) {
throw new IllegalArgumentException("message headers must not be null");
}
if (input.size() > MAX_COUNT) {
throw new IllegalArgumentException("message header count exceeds 64: " + input.size());
}
int bytes = 0;
Map<HeaderName, HeaderValue> copy = new LinkedHashMap<>();
Set<String> seen = new java.util.HashSet<>();
for (Map.Entry<HeaderName, HeaderValue> entry : input.entrySet()) {
HeaderName name = entry.getKey();
HeaderValue value = entry.getValue();
if (name == null || value == null) {
throw new IllegalArgumentException("message header name and value must not be null");
}
String normalized = name.normalized();
if (!reservedAllowed && ReservedHeaders.isReserved(normalized)) {
throw new IllegalArgumentException("message header is not allowed: " + normalized);
}
if (SECRET_NAMES.contains(normalized)) {
throw new IllegalArgumentException("message header is not allowed: " + normalized);
}
if (!seen.add(normalized)) {
throw new IllegalArgumentException("duplicate message header name: " + normalized);
}
bytes += name.value().getBytes(StandardCharsets.UTF_8).length;
bytes += value.value().getBytes(StandardCharsets.UTF_8).length;
copy.put(name, value);
}
if (bytes > MAX_TOTAL_BYTES) {
throw new IllegalArgumentException("message header bytes exceed 32768: " + bytes);
}
return new MessageHeaders(Collections.unmodifiableMap(copy));
}
/**
* Returns the headers as an immutable map.
*
* @return the header entries in insertion order
*/
public Map<HeaderName, HeaderValue> asMap() {
return values;
}
/**
* Looks a header up case-insensitively.
*
* @param name the header name in any case
* @return the value when present
*/
public Optional<HeaderValue> find(String name) {
if (name == null) {
return Optional.empty();
}
String normalized = name.toLowerCase(Locale.ROOT);
return values.entrySet().stream()
.filter(entry -> entry.getKey().normalized().equals(normalized))
.map(Map.Entry::getValue)
.findFirst();
}
/**
* Returns the number of headers.
*
* @return the entry count
*/
public int size() {
return values.size();
}
@Override
public boolean equals(Object other) {
return other instanceof MessageHeaders headers && values.equals(headers.values);
}
@Override
public int hashCode() {
return values.hashCode();
}
@Override
public String toString() {
return "MessageHeaders[size=" + values.size() + "]";
}
}
@@ -0,0 +1,126 @@
package dev.caskeleton.messaging.api.header;
import java.util.Locale;
import java.util.Set;
/**
* The header names the platform owns.
*
* <p>These carry envelope identity, trace propagation, and redrive bookkeeping. Applications cannot
* write them: if a caller could set {@code msg.id}, the logical identity that Inbox deduplication
* and DLQ correlation depend on would become caller-controlled.
*/
public final class ReservedHeaders {
/** Logical message identity. */
public static final String MESSAGE_ID = "msg.id";
/** Stable catalog message type. */
public static final String MESSAGE_TYPE = "msg.type";
/** Schema revision of the payload. */
public static final String SCHEMA_VERSION = "msg.schema-version";
/** Logical producing service. */
public static final String PRODUCER = "msg.producer";
/** Instant the platform created the envelope. */
public static final String PRODUCED_AT = "msg.produced-at";
/** Instant the business fact occurred. */
public static final String OCCURRED_AT = "msg.occurred-at";
/** Workflow correlation value. */
public static final String CORRELATION_ID = "msg.correlation-id";
/** Identity of the directly causing message. */
public static final String CAUSATION_ID = "msg.causation-id";
/** Codec content type. */
public static final String CONTENT_TYPE = "msg.content-type";
/** Distribution key. */
public static final String PARTITION_KEY = "msg.partition-key";
/** Ordering key. */
public static final String ORDERING_KEY = "msg.ordering-key";
/** Identity of the redrive operation that replayed this message. */
public static final String REDRIVE_ID = "msg.redrive-id";
/** How many times this message has been redriven. */
public static final String REDRIVE_COUNT = "msg.redrive-count";
/** Current retry attempt, counting the first delivery as one. */
public static final String RETRY_ATTEMPT = "msg.retry-attempt";
/** Instant of the first recorded failure. */
public static final String FIRST_FAILURE_AT = "msg.first-failure-at";
/** Instant of the most recent recorded failure. */
public static final String LAST_FAILURE_AT = "msg.last-failure-at";
/** Stable failure category recorded when parking or dead lettering. */
public static final String FAILURE_CATEGORY = "msg.failure-category";
/** Stable failure code recorded when parking or dead lettering. */
public static final String FAILURE_CODE = "msg.failure-code";
/** Logical destination the message was originally published to. */
public static final String ORIGIN_DESTINATION = "msg.origin-destination";
/** W3C trace parent. */
public static final String TRACEPARENT = "traceparent";
/** W3C trace state. */
public static final String TRACESTATE = "tracestate";
/** W3C baggage. */
public static final String BAGGAGE = "baggage";
private static final Set<String> NAMES =
Set.of(
MESSAGE_ID,
MESSAGE_TYPE,
SCHEMA_VERSION,
PRODUCER,
PRODUCED_AT,
OCCURRED_AT,
CORRELATION_ID,
CAUSATION_ID,
CONTENT_TYPE,
PARTITION_KEY,
ORDERING_KEY,
REDRIVE_ID,
REDRIVE_COUNT,
RETRY_ATTEMPT,
FIRST_FAILURE_AT,
LAST_FAILURE_AT,
FAILURE_CATEGORY,
FAILURE_CODE,
ORIGIN_DESTINATION,
TRACEPARENT,
TRACESTATE,
BAGGAGE);
private ReservedHeaders() {}
/**
* Reports whether a header name belongs to the platform.
*
* @param name the header name in any case
* @return true when the platform owns the name
*/
public static boolean isReserved(String name) {
return name != null && NAMES.contains(name.toLowerCase(Locale.ROOT));
}
/**
* Returns every reserved header name.
*
* @return an immutable set of lowercase names
*/
public static Set<String> names() {
return NAMES;
}
}
@@ -0,0 +1,25 @@
package dev.caskeleton.messaging.api.publish;
import java.util.List;
import java.util.concurrent.CompletionStage;
/**
* The M2 batch publish entry point.
*
* <p>A batch is a throughput optimisation, not a transaction. Entries succeed, fail, and go
* ambiguous independently, and {@link BatchPublishResult} keeps every entry's outcome against its
* submission index so the caller can act per entry. Nothing here rolls back: an adapter that
* reported a confirmed entry cannot un-publish it because a later entry was rejected.
*/
public interface BatchMessagePublisher {
/**
* Publishes a batch of independent requests.
*
* @param requests the entries to publish, in submission order
* @param options the batch-wide options
* @return a stage completing with one outcome per submitted entry
*/
CompletionStage<BatchPublishResult> publish(
List<PublishRequest<?>> requests, BatchPublishOptions options);
}
@@ -0,0 +1,27 @@
package dev.caskeleton.messaging.api.publish;
import dev.caskeleton.messaging.api.MessageId;
import java.util.Objects;
/**
* One item's outcome inside a batch publish.
*
* <p>Kept per index rather than collapsed into a batch-level success flag. A batch is not a
* transaction: some items confirm, some are rejected, and some are ambiguous, and the caller has to
* be able to act differently on each. A single boolean would force it to re-submit everything,
* which duplicates the items that already landed.
*
* @param index the item's position in the submitted list
* @param messageId the item's logical identity
* @param result the item's outcome and evidence
*/
public record BatchPublishItemResult(int index, MessageId messageId, PublishResult result) {
public BatchPublishItemResult {
Objects.requireNonNull(messageId, "messageId must not be null");
Objects.requireNonNull(result, "result must not be null");
if (index < 0) {
throw new IllegalArgumentException("index must not be negative");
}
}
}
@@ -0,0 +1,42 @@
package dev.caskeleton.messaging.api.publish;
import java.time.Duration;
import java.util.Objects;
/**
* Options covering a whole batch publish.
*
* <p>There is no retry setting. A batch is not a transaction, and retrying the batch would resubmit
* entries that already confirmed, so the platform never retries one on the caller's behalf; the
* caller resubmits the individual entries it knows are duplicate-safe under their original {@code
* messageId}.
*
* @param timeout the deadline for the whole batch
* @param maxBatchSize the largest number of entries accepted in one call
* @param stopOnFirstRejection whether to skip remaining entries once one is rejected
*/
public record BatchPublishOptions(
Duration timeout, int maxBatchSize, boolean stopOnFirstRejection) {
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(30);
private static final int DEFAULT_MAX_BATCH_SIZE = 500;
public BatchPublishOptions {
Objects.requireNonNull(timeout, "timeout must not be null");
if (timeout.isNegative() || timeout.isZero()) {
throw new IllegalArgumentException("batch timeout must be positive");
}
if (maxBatchSize < 1) {
throw new IllegalArgumentException("maxBatchSize must be at least 1");
}
}
/**
* Returns the defaults: thirty seconds, 500 entries, best-effort completion of every entry.
*
* @return the default options
*/
public static BatchPublishOptions defaults() {
return new BatchPublishOptions(DEFAULT_TIMEOUT, DEFAULT_MAX_BATCH_SIZE, false);
}
}
@@ -0,0 +1,44 @@
package dev.caskeleton.messaging.api.publish;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
/**
* The outcome of one batch publish.
*
* <p>There is no automatic batch retry. Re-submitting a whole batch because part of it failed
* duplicates the part that succeeded; the caller re-submits only the items it decides are
* duplicate-safe, under their original message ids.
*
* @param items each item's outcome, in submission order
* @param elapsed how long the batch took
*/
public record BatchPublishResult(List<BatchPublishItemResult> items, Duration elapsed) {
public BatchPublishResult {
Objects.requireNonNull(items, "items must not be null");
Objects.requireNonNull(elapsed, "elapsed must not be null");
items = List.copyOf(items);
}
/**
* Returns the items with a given completion.
*
* @param completion the completion to select
* @return the matching items
*/
public List<BatchPublishItemResult> withCompletion(PublishCompletion completion) {
return items.stream().filter(item -> item.result().completion() == completion).toList();
}
/**
* Reports whether every item confirmed.
*
* @return true when nothing was rejected or ambiguous
*/
public boolean allConfirmed() {
return items.stream()
.allMatch(item -> item.result().completion() == PublishCompletion.CONFIRMED);
}
}
@@ -0,0 +1,30 @@
package dev.caskeleton.messaging.api.publish;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.destination.MessageDestination;
/**
* The blocking facade over the asynchronous publisher.
*
* <p>Offered because most business code is written against a blocking data access layer, and
* forcing a {@code CompletionStage} through it produces worse code than a blocking call does. It is
* a facade rather than a second implementation: the core stays asynchronous, and this only converts
* the lifecycle.
*
* <p>It respects the publish deadline rather than waiting indefinitely, so a stalled broker
* surfaces as a timeout with ambiguous evidence instead of an exhausted thread pool.
*/
public interface BlockingMessagePublisher {
/**
* Publishes one message and waits for its outcome.
*
* @param <T> the payload type
* @param destination the logical destination
* @param message the envelope to publish
* @param options per-call options, including the deadline
* @return the outcome and its evidence
*/
<T> PublishResult publish(
MessageDestination<T> destination, MessageEnvelope<T> message, PublishOptions options);
}
@@ -0,0 +1,27 @@
package dev.caskeleton.messaging.api.publish;
import java.util.Map;
/**
* A broker-specific coordinate for a published or delivered message.
*
* <p>Positions exist for diagnostics and replay. Business logic must not branch on them: the whole
* point of the logical destination model is that a handler behaves identically whether it is
* reading a Kafka offset or a RabbitMQ delivery tag.
*/
public interface BrokerPosition {
/**
* Returns the broker family that produced this position.
*
* @return a stable, low-cardinality broker name
*/
String broker();
/**
* Returns the position as diagnostic attributes.
*
* @return an immutable map safe for structured logs
*/
Map<String, String> diagnosticAttributes();
}
@@ -0,0 +1,20 @@
package dev.caskeleton.messaging.api.publish;
/**
* The strength of confirmation the broker actually supplied.
*
* <p>Kept separate from the requested confirmation requirement so that "we asked for replication
* and got a leader ack" is representable, and therefore rejectable, instead of being rounded up to
* success.
*/
public enum ConfirmationLevel {
/** No confirmation was received. */
NONE,
/** The broker acknowledged receipt without proving durability. */
BROKER_ACK,
/** The broker acknowledged replication or persistence. */
REPLICATION_OR_PERSISTENCE_ACK
}
@@ -0,0 +1,28 @@
package dev.caskeleton.messaging.api.publish;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.destination.MessageDestination;
import java.time.Instant;
import java.util.concurrent.CompletionStage;
/**
* The M2 scheduled-delivery entry point.
*
* <p>Only destinations whose runtime declares {@code delayedDelivery} accept these calls. A plain
* Kafka topic does not: emulating a delay by holding the message in the producer would make the
* publisher's own liveness the schedule, so the platform rejects the call instead of pretending.
*/
public interface DelayedMessagePublisher {
/**
* Publishes a message the broker must not deliver before the given instant.
*
* @param <T> the payload type
* @param destination the logical destination
* @param message the envelope to publish
* @param deliverAt the earliest delivery time
* @return a stage completing with the publish outcome and its evidence
*/
<T> CompletionStage<PublishResult> publish(
MessageDestination<T> destination, MessageEnvelope<T> message, Instant deliverAt);
}
@@ -0,0 +1,26 @@
package dev.caskeleton.messaging.api.publish;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.destination.MessageDestination;
import java.util.concurrent.CompletionStage;
/**
* The M1 typed publish entry point used by ordinary business code.
*
* <p>The core contract is {@link CompletionStage}. Blocking and Reactor facades live in separate
* modules so that {@code messaging-core-api} keeps no dependency on either programming model.
*/
public interface MessagePublisher {
/**
* Publishes one message.
*
* @param <T> the payload type
* @param destination the logical destination
* @param message the envelope to publish
* @param options per-call options
* @return a stage completing with the outcome and its evidence
*/
<T> CompletionStage<PublishResult> publish(
MessageDestination<T> destination, MessageEnvelope<T> message, PublishOptions options);
}
@@ -0,0 +1,20 @@
package dev.caskeleton.messaging.api.publish;
/**
* How a publish attempt ended.
*
* <p>Publish is not a boolean. Collapsing "the broker refused this" and "we never learned what the
* broker did" into one failure is what produces duplicate orders: the first is safe to abandon, the
* second is not safe to retry with a new identity.
*/
public enum PublishCompletion {
/** The broker accepted the message at the required confirmation level. */
CONFIRMED,
/** The message was definitively not accepted. It is safe to abandon this attempt. */
REJECTED,
/** The outcome is unknown. The broker may or may not hold the message. */
AMBIGUOUS
}
@@ -0,0 +1,27 @@
package dev.caskeleton.messaging.api.publish;
import java.time.Duration;
import java.util.Objects;
/**
* Requests broker-side duplicate suppression for a publish.
*
* <p>The deduplication key defaults to the logical message id, which is what makes an Outbox relay
* able to retry an ambiguous publish without creating a second message. Requesting this on a broker
* without the {@code deduplicatedPublish} capability is a startup failure, not a silent no-op.
*
* @param key the stable deduplication key
* @param window how long the broker should remember the key
*/
public record PublishDeduplication(String key, Duration window) {
public PublishDeduplication {
Objects.requireNonNull(window, "deduplication window must not be null");
if (key == null || key.isBlank()) {
throw new IllegalArgumentException("deduplication key must not be blank");
}
if (window.isNegative() || window.isZero()) {
throw new IllegalArgumentException("deduplication window must be positive");
}
}
}
@@ -0,0 +1,66 @@
package dev.caskeleton.messaging.api.publish;
import java.util.Objects;
/**
* The observable facts behind a publish outcome.
*
* <p>Evidence is recorded before a completion is chosen, not derived from it. That ordering is what
* lets an operator answer "could the broker be holding this message?" from a stored result.
*
* @param queuedLocally the adapter buffered the message in process
* @param transmission what is known about bytes reaching the broker
* @param brokerAccepted the broker positively acknowledged the message
* @param confirmationLevel the strength of that acknowledgement
*/
public record PublishEvidence(
boolean queuedLocally,
TransmissionEvidence transmission,
boolean brokerAccepted,
ConfirmationLevel confirmationLevel) {
public PublishEvidence {
Objects.requireNonNull(transmission, "transmission must not be null");
Objects.requireNonNull(confirmationLevel, "confirmationLevel must not be null");
if (!brokerAccepted && confirmationLevel != ConfirmationLevel.NONE) {
throw new IllegalArgumentException(
"confirmation level requires broker acceptance: " + confirmationLevel);
}
if (transmission == TransmissionEvidence.NOT_TRANSMITTED && brokerAccepted) {
throw new IllegalArgumentException("untransmitted message cannot be broker accepted");
}
}
/**
* Returns evidence for a message rejected before anything was sent.
*
* @return local rejection evidence
*/
public static PublishEvidence notTransmitted() {
return new PublishEvidence(
false, TransmissionEvidence.NOT_TRANSMITTED, false, ConfirmationLevel.NONE);
}
/**
* Returns evidence for a message whose fate is unknown.
*
* @return ambiguous evidence
*/
public static PublishEvidence ambiguous() {
return new PublishEvidence(
true, TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED, false, ConfirmationLevel.NONE);
}
/**
* Returns evidence for a confirmed publish.
*
* @param level the confirmation the broker supplied
* @return confirmed evidence
*/
public static PublishEvidence confirmed(ConfirmationLevel level) {
if (level == ConfirmationLevel.NONE) {
throw new IllegalArgumentException("confirmed evidence requires a confirmation level");
}
return new PublishEvidence(true, TransmissionEvidence.TRANSMITTED, true, level);
}
}
@@ -0,0 +1,61 @@
package dev.caskeleton.messaging.api.publish;
import dev.caskeleton.messaging.api.destination.ConfirmationRequirement;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
/**
* Per-call publish options.
*
* <p>{@code brokerHints} must be empty for M1 callers. Only an M3 native capability may populate
* it, because a hint map on the general API becomes an escape hatch that quietly bypasses
* destination policy.
*
* @param timeout the publish operation deadline
* @param confirmation the confirmation this call requires
* @param deduplication optional broker-side duplicate suppression
* @param brokerHints M3-only adapter hints
*/
public record PublishOptions(
Duration timeout,
ConfirmationRequirement confirmation,
Optional<PublishDeduplication> deduplication,
Map<String, String> brokerHints) {
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(5);
public PublishOptions {
Objects.requireNonNull(timeout, "timeout must not be null");
Objects.requireNonNull(confirmation, "confirmation must not be null");
Objects.requireNonNull(deduplication, "deduplication must not be null");
Objects.requireNonNull(brokerHints, "brokerHints must not be null");
if (timeout.isNegative() || timeout.isZero()) {
throw new IllegalArgumentException("publish timeout must be positive");
}
brokerHints = Map.copyOf(brokerHints);
}
/**
* Returns the M1 default: five second timeout, replication evidence, no hints.
*
* @return the default options
*/
public static PublishOptions defaults() {
return new PublishOptions(
DEFAULT_TIMEOUT,
ConfirmationRequirement.REPLICATION_OR_PERSISTENCE_ACK,
Optional.empty(),
Map.of());
}
/**
* Reports whether these options stay inside the M1 surface.
*
* @return true when no broker hints are present
*/
public boolean isM1Compatible() {
return brokerHints.isEmpty();
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.messaging.api.publish;
import dev.caskeleton.messaging.api.MessageEnvelope;
import dev.caskeleton.messaging.api.destination.MessageDestination;
import java.util.Objects;
/**
* One entry of a batch publish, pairing a destination with the envelope bound for it.
*
* <p>A batch is a list of independent publishes, not one publish of many payloads, so each entry
* carries its own destination. Nothing forces the entries of a batch to share a destination; an
* adapter groups them itself when its wire protocol rewards grouping.
*
* @param <T> the payload type
* @param destination the logical destination for this entry
* @param message the envelope to publish
* @param options the per-entry options
*/
public record PublishRequest<T>(
MessageDestination<T> destination, MessageEnvelope<T> message, PublishOptions options) {
public PublishRequest {
Objects.requireNonNull(destination, "destination must not be null");
Objects.requireNonNull(message, "message must not be null");
Objects.requireNonNull(options, "options must not be null");
}
/**
* Creates a request using the default publish options.
*
* @param <T> the payload type
* @param destination the logical destination
* @param message the envelope to publish
* @return the request
*/
public static <T> PublishRequest<T> of(
MessageDestination<T> destination, MessageEnvelope<T> message) {
return new PublishRequest<>(destination, message, PublishOptions.defaults());
}
}
@@ -0,0 +1,88 @@
package dev.caskeleton.messaging.api.publish;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
/**
* The outcome of one publish call, with the evidence that justifies it.
*
* <p>The constructor refuses combinations that would let a caller read a stronger guarantee than
* was actually obtained. An adapter that cannot decide must report {@link
* PublishCompletion#AMBIGUOUS} with no confirmation level, which is the conservative answer, rather
* than picking a completion that happens to make the call site simpler.
*
* @param completion how the attempt ended
* @param evidence the observable facts behind that outcome
* @param routingOutcome whether the broker routed the message
* @param position the broker coordinate when known
* @param attempts transport attempts made, counting the first as one
* @param elapsed wall-clock time spent
* @param failure the sanitized failure when the attempt did not confirm
*/
public record PublishResult(
PublishCompletion completion,
PublishEvidence evidence,
RoutingOutcome routingOutcome,
Optional<BrokerPosition> position,
int attempts,
Duration elapsed,
Optional<FailureDescriptor> failure) {
public PublishResult {
Objects.requireNonNull(completion, "completion must not be null");
Objects.requireNonNull(evidence, "evidence must not be null");
Objects.requireNonNull(routingOutcome, "routingOutcome must not be null");
Objects.requireNonNull(position, "position must not be null");
Objects.requireNonNull(elapsed, "elapsed must not be null");
Objects.requireNonNull(failure, "failure must not be null");
if (attempts < 1) {
throw new IllegalArgumentException("publish attempts must be at least 1");
}
if (elapsed.isNegative()) {
throw new IllegalArgumentException("publish elapsed must not be negative");
}
if (completion == PublishCompletion.CONFIRMED && !evidence.brokerAccepted()) {
throw new IllegalArgumentException("confirmed publish requires broker acceptance");
}
if (completion == PublishCompletion.CONFIRMED
&& evidence.confirmationLevel() == ConfirmationLevel.NONE) {
throw new IllegalArgumentException("confirmed publish requires a confirmation level");
}
if (completion == PublishCompletion.CONFIRMED && routingOutcome == RoutingOutcome.UNROUTABLE) {
throw new IllegalArgumentException("unroutable publish cannot be confirmed");
}
if (completion == PublishCompletion.AMBIGUOUS
&& evidence.confirmationLevel() != ConfirmationLevel.NONE) {
throw new IllegalArgumentException("ambiguous publish cannot claim confirmation");
}
if (completion == PublishCompletion.AMBIGUOUS && evidence.brokerAccepted()) {
throw new IllegalArgumentException("ambiguous publish cannot claim broker acceptance");
}
if (completion == PublishCompletion.AMBIGUOUS
&& evidence.transmission() == TransmissionEvidence.NOT_TRANSMITTED) {
throw new IllegalArgumentException("untransmitted publish is rejected, not ambiguous");
}
if (completion != PublishCompletion.CONFIRMED && failure.isEmpty()) {
throw new IllegalArgumentException("non-confirmed publish requires a failure descriptor");
}
if (completion == PublishCompletion.CONFIRMED && failure.isPresent()) {
throw new IllegalArgumentException("confirmed publish must not carry a failure descriptor");
}
}
/**
* Reports whether the broker may be holding this message.
*
* <p>Callers use this to decide between abandoning an attempt and re-publishing under the same
* logical id.
*
* @return true when the outcome is ambiguous
*/
public boolean mayHaveBeenStored() {
return completion == PublishCompletion.AMBIGUOUS;
}
}
@@ -0,0 +1,23 @@
package dev.caskeleton.messaging.api.publish;
/**
* Whether the broker could route the message to a destination.
*
* <p>Routing is separate from confirmation because RabbitMQ can confirm a publish the exchange
* accepted and simultaneously return it as unroutable. Reporting only the confirm would turn a
* dropped message into a success.
*/
public enum RoutingOutcome {
/** The broker has no routing stage, as with a Kafka topic publish. */
NOT_APPLICABLE,
/** The message reached at least one destination. */
ROUTED,
/** The broker accepted the publish but found no destination. */
UNROUTABLE,
/** Routing could not be determined. */
UNKNOWN
}
@@ -0,0 +1,14 @@
package dev.caskeleton.messaging.api.publish;
/** What the adapter can prove about bytes leaving the process. */
public enum TransmissionEvidence {
/** Nothing was written to the broker connection. */
NOT_TRANSMITTED,
/** Bytes may have been written; the connection failed before that could be established. */
MAY_HAVE_BEEN_TRANSMITTED,
/** Bytes were written to the broker connection. */
TRANSMITTED
}
@@ -0,0 +1,25 @@
package dev.caskeleton.messaging.api.settlement;
import dev.caskeleton.messaging.api.delivery.MessageDelivery;
import java.util.concurrent.CompletionStage;
/**
* The M2 handler that settles its own deliveries.
*
* <p>Available only to modules granted the advanced capability. A handler that returns without
* calling a terminal settlement method is a defect the runtime detects and reports rather than
* silently leaving the message in flight.
*
* @param <T> the payload type
*/
public interface ManualMessageHandler<T> {
/**
* Handles one delivery, settling it through the supplied controller.
*
* @param delivery the decoded message and its metadata
* @param settlement the settlement handle for this delivery
* @return a stage completing when handling has finished
*/
CompletionStage<Void> handle(MessageDelivery<T> delivery, SettlementController settlement);
}
@@ -0,0 +1,14 @@
package dev.caskeleton.messaging.api.settlement;
/** How a settlement attempt ended. */
public enum SettlementCompletion {
/** The broker confirmed the settlement. */
SETTLED,
/** The broker refused the settlement. */
REJECTED,
/** The settlement outcome is unknown and redelivery remains possible. */
UNKNOWN
}
@@ -0,0 +1,50 @@
package dev.caskeleton.messaging.api.settlement;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import java.time.Duration;
import java.util.concurrent.CompletionStage;
/**
* The M2 manual settlement handle.
*
* <p>No method here accepts a broker channel, delivery tag, or offset. Manual settlement changes
* <em>when</em> the platform settles, never <em>who</em> settles, so the same DLQ-before-ack
* ordering and payload limits still apply.
*
* <p>Exactly one terminal call is permitted per delivery; a second call fails rather than racing
* the first.
*/
public interface SettlementController {
/**
* Acknowledges the message.
*
* @return a stage completing with the settlement outcome
*/
CompletionStage<SettlementResult> ack();
/**
* Schedules the message for another attempt.
*
* @param delay how long to wait before redelivery
* @return a stage completing with the settlement outcome
*/
CompletionStage<SettlementResult> retry(Duration delay);
/**
* Routes the message to the dead letter destination, settling the source only after that publish
* is confirmed.
*
* @param failure the sanitized failure description
* @return a stage completing with the settlement outcome
*/
CompletionStage<SettlementResult> deadLetter(FailureDescriptor failure);
/**
* Discards the message without dead lettering.
*
* @param failure the sanitized failure description
* @return a stage completing with the settlement outcome
*/
CompletionStage<SettlementResult> reject(FailureDescriptor failure);
}
@@ -0,0 +1,66 @@
package dev.caskeleton.messaging.api.settlement;
import java.util.Objects;
/**
* What is known about a settlement reaching the broker.
*
* @param transmitted the settlement was written to the broker connection
* @param brokerConfirmed the broker confirmed the settlement
* @param redeliveryPossible the message may still be redelivered
*/
public record SettlementEvidence(
boolean transmitted, boolean brokerConfirmed, boolean redeliveryPossible) {
public SettlementEvidence {
if (brokerConfirmed && !transmitted) {
throw new IllegalArgumentException("an unsent settlement cannot be broker confirmed");
}
}
/**
* Returns evidence for a confirmed settlement.
*
* @return confirmed evidence
*/
public static SettlementEvidence confirmed() {
return new SettlementEvidence(true, true, false);
}
/**
* Returns evidence for a settlement whose fate is unknown.
*
* @return unknown evidence
*/
public static SettlementEvidence unknown() {
return new SettlementEvidence(true, false, true);
}
/**
* Returns evidence for a settlement that never left the process.
*
* @return unsent evidence
*/
public static SettlementEvidence notTransmitted() {
return new SettlementEvidence(false, false, true);
}
/**
* Returns a settlement evidence value, validating the combination.
*
* @param object the value to compare
* @return whether the values are equal
*/
@Override
public boolean equals(Object object) {
return object instanceof SettlementEvidence other
&& transmitted == other.transmitted
&& brokerConfirmed == other.brokerConfirmed
&& redeliveryPossible == other.redeliveryPossible;
}
@Override
public int hashCode() {
return Objects.hash(transmitted, brokerConfirmed, redeliveryPossible);
}
}
@@ -0,0 +1,47 @@
package dev.caskeleton.messaging.api.settlement;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import java.util.Objects;
import java.util.Optional;
/**
* The outcome of one settlement call.
*
* <p>{@link SettlementCompletion#UNKNOWN} means redelivery remains possible and must not be read as
* success. Treating an unconfirmed acknowledgement as settled is the classic route to a message
* that looks processed in logs and is processed again minutes later.
*
* @param completion how the settlement ended
* @param evidence what is known about it reaching the broker
* @param failure the sanitized failure when settlement did not confirm
*/
public record SettlementResult(
SettlementCompletion completion,
SettlementEvidence evidence,
Optional<FailureDescriptor> failure) {
public SettlementResult {
Objects.requireNonNull(completion, "completion must not be null");
Objects.requireNonNull(evidence, "evidence must not be null");
Objects.requireNonNull(failure, "failure must not be null");
if (completion == SettlementCompletion.SETTLED && !evidence.brokerConfirmed()) {
throw new IllegalArgumentException("settled result requires broker confirmation");
}
if (completion == SettlementCompletion.SETTLED && evidence.redeliveryPossible()) {
throw new IllegalArgumentException("settled result cannot leave redelivery possible");
}
if (completion != SettlementCompletion.SETTLED && failure.isEmpty()) {
throw new IllegalArgumentException("non-settled result requires a failure descriptor");
}
}
/**
* Returns a confirmed settlement result.
*
* @return a settled result
*/
public static SettlementResult settled() {
return new SettlementResult(
SettlementCompletion.SETTLED, SettlementEvidence.confirmed(), Optional.empty());
}
}
@@ -0,0 +1,60 @@
package dev.caskeleton.messaging.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.delivery.DeliveryGuarantee;
import dev.caskeleton.messaging.api.delivery.OrderingScope;
import java.util.Arrays;
import java.util.UUID;
import org.junit.jupiter.api.Test;
class CoreValueTypesTest {
@Test
void messageTypeRejectsBlankValue() {
assertThatThrownBy(() -> new MessageType(" ")).isInstanceOf(IllegalArgumentException.class);
}
@Test
void schemaVersionMustBePositive() {
assertThatThrownBy(() -> new SchemaVersion(0)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void guaranteeEnumsDoNotAdvertiseUnsupportedSemantics() {
assertThat(Arrays.stream(DeliveryGuarantee.values()).map(Enum::name))
.doesNotContain("EXACTLY_ONCE");
assertThat(Arrays.stream(OrderingScope.values()).map(Enum::name)).doesNotContain("GLOBAL");
}
@Test
void newMessageIdIsVersionSevenAndTimeOrdered() {
MessageId first = MessageId.newId();
MessageId second = MessageId.newId();
assertThat(first.value().version()).isEqualTo(7);
assertThat(first.value().variant()).isEqualTo(2);
assertThat(first.value().compareTo(second.value())).isNegative();
}
@Test
void messageIdRejectsNullValue() {
assertThatThrownBy(() -> new MessageId(null)).isInstanceOf(NullPointerException.class);
}
@Test
void causationIdWrapsAPredecessorMessageId() {
MessageId predecessor = new MessageId(UUID.fromString("0190f4aa-0000-7000-8000-000000000001"));
assertThat(new CausationId(predecessor).value()).isEqualTo(predecessor);
}
@Test
void producerAndCorrelationIdentifiersStayBounded() {
assertThatThrownBy(() -> new ProducerId("p".repeat(121)))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new CorrelationId("c".repeat(161)))
.isInstanceOf(IllegalArgumentException.class);
}
}
@@ -0,0 +1,141 @@
package dev.caskeleton.messaging.api;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.header.HeaderName;
import dev.caskeleton.messaging.api.header.HeaderValue;
import dev.caskeleton.messaging.api.header.MessageHeaders;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.Test;
class MessageEnvelopeTest {
@Test
void applicationCannotSetReservedHeader() {
Map<HeaderName, HeaderValue> forged =
Map.of(new HeaderName("msg.id"), new HeaderValue("forged"));
assertThatThrownBy(() -> MessageHeaders.application(forged))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void reservedHeaderRejectionIsCaseInsensitive() {
Map<HeaderName, HeaderValue> forged =
Map.of(new HeaderName("MSG.Id"), new HeaderValue("forged"));
assertThatThrownBy(() -> MessageHeaders.application(forged))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void platformMayWriteReservedHeaders() {
MessageHeaders headers =
MessageHeaders.platform(Map.of(new HeaderName("msg.id"), new HeaderValue("0190f4aa")));
assertThat(headers.find("MSG.ID")).map(HeaderValue::value).hasValue("0190f4aa");
}
@Test
void secretHeadersAreRejected() {
Map<HeaderName, HeaderValue> secret =
Map.of(new HeaderName("Authorization"), new HeaderValue("Bearer secret"));
assertThatThrownBy(() -> MessageHeaders.application(secret))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void platformCannotWriteSecretHeadersEither() {
Map<HeaderName, HeaderValue> secret =
Map.of(new HeaderName("client_secret"), new HeaderValue("s3cr3t"));
assertThatThrownBy(() -> MessageHeaders.platform(secret))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void headerCountAboveSixtyFourIsRejected() {
Map<HeaderName, HeaderValue> tooMany = new LinkedHashMap<>();
for (int i = 0; i < 65; i++) {
tooMany.put(new HeaderName("h" + i), new HeaderValue("v"));
}
assertThatThrownBy(() -> MessageHeaders.application(tooMany))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("64");
}
@Test
void headerBytesAboveThirtyTwoKibibytesAreRejected() {
Map<HeaderName, HeaderValue> heavy = new LinkedHashMap<>();
for (int i = 0; i < 16; i++) {
heavy.put(new HeaderName("h" + i), new HeaderValue("v".repeat(4096)));
}
assertThatThrownBy(() -> MessageHeaders.application(heavy))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("32768");
}
@Test
void headerNameAboveOneHundredTwentyEightBytesIsRejected() {
assertThatThrownBy(() -> new HeaderName("n".repeat(129)))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void headerValueAboveFourKibibytesIsRejected() {
assertThatThrownBy(() -> new HeaderValue("v".repeat(4097)))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void payloadCannotBeNull() {
assertThatThrownBy(() -> TestEnvelopeFactory.envelope(null))
.isInstanceOf(NullPointerException.class);
}
@Test
void withPayloadPreservesLogicalIdentity() {
MessageEnvelope<String> original = TestEnvelopeFactory.envelope("original");
MessageEnvelope<byte[]> encoded = original.withPayload(new byte[] {1, 2, 3});
assertThat(encoded.messageId()).isEqualTo(original.messageId());
assertThat(encoded.messageType()).isEqualTo(original.messageType());
assertThat(encoded.schemaVersion()).isEqualTo(original.schemaVersion());
}
}
/**
* Builds envelopes for tests. Package-private on purpose: production code must go through the
* publisher, which is what applies destination policy.
*/
final class TestEnvelopeFactory {
private TestEnvelopeFactory() {}
static <T> MessageEnvelope<T> envelope(T payload) {
return new MessageEnvelope<>(
MessageId.newId(),
new MessageType("order.created"),
new SchemaVersion(1),
Instant.parse("2026-08-10T00:00:00Z"),
Optional.of(Instant.parse("2026-08-10T00:00:00Z")),
new ProducerId("order-api"),
Optional.empty(),
Optional.empty(),
ContentType.JSON,
Optional.empty(),
Optional.empty(),
Optional.empty(),
TraceContext.none(),
MessageHeaders.empty(),
payload);
}
}
@@ -0,0 +1,13 @@
package dev.caskeleton.messaging.api;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class ModuleSmokeTest {
@Test
void coreApiModuleLoads() {
assertThat(ModuleSmokeTest.class.getPackageName()).isEqualTo("dev.caskeleton.messaging.api");
}
}
@@ -0,0 +1,129 @@
package dev.caskeleton.messaging.api.delivery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.destination.DestinationName;
import dev.caskeleton.messaging.api.error.FailureCategory;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import dev.caskeleton.messaging.api.settlement.SettlementCompletion;
import dev.caskeleton.messaging.api.settlement.SettlementEvidence;
import dev.caskeleton.messaging.api.settlement.SettlementResult;
import java.time.Instant;
import java.util.Optional;
import org.junit.jupiter.api.Test;
class ConsumerContractTest {
@Test
void retryCarriesStableFailureCategory() {
FailureDescriptor failure =
new FailureDescriptor(
FailureCategory.PROCESSING_TRANSIENT,
"DOWNSTREAM_TIMEOUT",
true,
"downstream timed out",
Optional.of("TimeoutException"));
HandleResult result = new HandleResult.Retry(failure);
assertThat(((HandleResult.Retry) result).failure().retryable()).isTrue();
}
@Test
void deliveryMetadataCountsInitialDeliveryAsAttemptOne() {
DeliveryMetadata metadata = DeliveryMetadataFixture.initial();
assertThat(metadata.deliveryAttempt()).isEqualTo(1);
assertThat(metadata.redelivered()).isFalse();
}
@Test
void firstDeliveryCannotBeFlaggedAsRedelivered() {
assertThatThrownBy(
() ->
new DeliveryMetadata(
new DestinationName("order-events"),
1,
true,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Instant.parse("2026-08-10T00:00:00Z")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void deliveryAttemptIsNeverZero() {
assertThatThrownBy(
() ->
new DeliveryMetadata(
new DestinationName("order-events"),
0,
false,
Optional.empty(),
Optional.empty(),
Optional.empty(),
Instant.parse("2026-08-10T00:00:00Z")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void handleResultPermitsExactlyTheFourDeclaredOutcomes() {
assertThat(HandleResult.class.getPermittedSubclasses())
.containsExactlyInAnyOrder(
HandleResult.Success.class,
HandleResult.Retry.class,
HandleResult.DeadLetter.class,
HandleResult.Reject.class);
}
@Test
void unknownSettlementIsNotSuccess() {
SettlementResult result =
new SettlementResult(
SettlementCompletion.UNKNOWN,
SettlementEvidence.unknown(),
Optional.of(
FailureDescriptor.of(
FailureCategory.AMBIGUOUS, "SETTLEMENT_UNKNOWN", "ack not confirmed")));
assertThat(result.completion()).isNotEqualTo(SettlementCompletion.SETTLED);
assertThat(result.evidence().redeliveryPossible()).isTrue();
}
@Test
void settledResultCannotLeaveRedeliveryPossible() {
assertThatThrownBy(
() ->
new SettlementResult(
SettlementCompletion.SETTLED, SettlementEvidence.unknown(), Optional.empty()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void deliveryContextReportsHandlerDeadlineExpiry() {
DeliveryContext context =
new DeliveryContext(Instant.parse("2026-08-10T00:00:30Z"), false, "order-projection");
assertThat(context.isExpired(Instant.parse("2026-08-10T00:00:29Z"))).isFalse();
assertThat(context.isExpired(Instant.parse("2026-08-10T00:00:30Z"))).isTrue();
}
}
/** Builds delivery metadata for tests without exposing a production factory. */
final class DeliveryMetadataFixture {
private DeliveryMetadataFixture() {}
static DeliveryMetadata initial() {
return new DeliveryMetadata(
new DestinationName("order-events"),
1,
false,
Optional.empty(),
Optional.of("order.events.v1-0"),
Optional.of("order-projection"),
Instant.parse("2026-08-10T00:00:00Z"));
}
}
@@ -0,0 +1,60 @@
package dev.caskeleton.messaging.api.destination;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.MessageType;
import org.junit.jupiter.api.Test;
class DestinationCapabilityTest {
@Test
void logicalDestinationDoesNotContainBrokerSpecificAddress() {
MessageDestination<String> destination =
new MessageDestination<>(
new DestinationName("order-events"), new MessageType("order.created"), String.class);
assertThat(destination.name().value()).isEqualTo("order-events");
}
@Test
void destinationNameRejectsBrokerSeparatorsAndWhitespace() {
assertThatThrownBy(() -> new DestinationName("topic://orders"))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new DestinationName("order events"))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> new DestinationName("Order-Events"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void emptyCapabilitySetAdvertisesNothing() {
MessagingCapabilities capabilities = MessagingCapabilities.none();
assertThat(capabilities.brokerAcknowledgement()).isFalse();
assertThat(capabilities.replay()).isFalse();
assertThat(capabilities.brokerTransaction()).isFalse();
}
@Test
void destinationCapabilitiesRequireABrokerName() {
MessagingCapabilities capabilities = MessagingCapabilities.none();
DestinationName name = new DestinationName("order-events");
assertThatThrownBy(() -> new DestinationCapabilities(name, " ", capabilities))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void destinationKindCoversEveryDeclaredInteractionPattern() {
assertThat(DestinationKind.values())
.containsExactly(
DestinationKind.ASYNC_COMMAND,
DestinationKind.DOMAIN_EVENT,
DestinationKind.INTEGRATION_EVENT,
DestinationKind.WORK_QUEUE,
DestinationKind.PUBLISH_SUBSCRIBE,
DestinationKind.EVENT_STREAM,
DestinationKind.REQUEST_REPLY);
}
}
@@ -0,0 +1,166 @@
package dev.caskeleton.messaging.api.publish;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.messaging.api.error.FailureCategory;
import dev.caskeleton.messaging.api.error.FailureDescriptor;
import java.time.Duration;
import java.util.Optional;
import org.junit.jupiter.api.Test;
class PublishResultTest {
private static final FailureDescriptor AMBIGUOUS_FAILURE =
FailureDescriptor.of(FailureCategory.AMBIGUOUS, "CONFIRM_TIMEOUT", "confirm timed out");
@Test
void confirmedResultRequiresBrokerAcceptance() {
PublishEvidence evidence =
new PublishEvidence(false, TransmissionEvidence.TRANSMITTED, false, ConfirmationLevel.NONE);
assertThatThrownBy(
() ->
new PublishResult(
PublishCompletion.CONFIRMED,
evidence,
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
Duration.ofMillis(10),
Optional.empty()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void evidenceCannotClaimConfirmationWithoutBrokerAcceptance() {
assertThatThrownBy(
() ->
new PublishEvidence(
true,
TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED,
false,
ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void ambiguousResultCannotClaimReplicationConfirmation() {
PublishEvidence evidence =
new PublishEvidence(
true,
TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED,
true,
ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK);
assertThatThrownBy(
() ->
new PublishResult(
PublishCompletion.AMBIGUOUS,
evidence,
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
Duration.ofSeconds(5),
Optional.of(AMBIGUOUS_FAILURE)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("ambiguous");
}
@Test
void confirmedResultCannotBeUnroutable() {
assertThatThrownBy(
() ->
new PublishResult(
PublishCompletion.CONFIRMED,
PublishEvidence.confirmed(ConfirmationLevel.BROKER_ACK),
RoutingOutcome.UNROUTABLE,
Optional.empty(),
1,
Duration.ofMillis(3),
Optional.empty()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void untransmittedPublishIsRejectedRatherThanAmbiguous() {
assertThatThrownBy(
() ->
new PublishResult(
PublishCompletion.AMBIGUOUS,
PublishEvidence.notTransmitted(),
RoutingOutcome.NOT_APPLICABLE,
Optional.empty(),
1,
Duration.ofMillis(1),
Optional.of(AMBIGUOUS_FAILURE)))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void nonConfirmedResultRequiresAFailureDescriptor() {
assertThatThrownBy(
() ->
new PublishResult(
PublishCompletion.REJECTED,
PublishEvidence.notTransmitted(),
RoutingOutcome.NOT_APPLICABLE,
Optional.empty(),
1,
Duration.ofMillis(1),
Optional.empty()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void confirmedPublishIsWellFormedAndNotAmbiguous() {
PublishResult result =
new PublishResult(
PublishCompletion.CONFIRMED,
PublishEvidence.confirmed(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK),
RoutingOutcome.ROUTED,
Optional.empty(),
1,
Duration.ofMillis(12),
Optional.empty());
assertThat(result.mayHaveBeenStored()).isFalse();
assertThat(result.evidence().confirmationLevel())
.isEqualTo(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK);
}
@Test
void ambiguousPublishReportsThatTheBrokerMayHoldTheMessage() {
PublishResult result =
new PublishResult(
PublishCompletion.AMBIGUOUS,
PublishEvidence.ambiguous(),
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
Duration.ofSeconds(5),
Optional.of(AMBIGUOUS_FAILURE));
assertThat(result.mayHaveBeenStored()).isTrue();
}
@Test
void attemptsCountTheFirstTransportAttemptAsOne() {
assertThatThrownBy(
() ->
new PublishResult(
PublishCompletion.CONFIRMED,
PublishEvidence.confirmed(ConfirmationLevel.BROKER_ACK),
RoutingOutcome.ROUTED,
Optional.empty(),
0,
Duration.ofMillis(1),
Optional.empty()))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void m1OptionsCarryNoBrokerHints() {
assertThat(PublishOptions.defaults().isM1Compatible()).isTrue();
}
}