refactor(repo)!: 들여온 플랫폼을 src/platforms 아래로 묶는다
문제: src/ 최상위에 계층 폴더와 들여온 제품 폴더(messaging, grpc,
grpc-advanced)와 optional 빌드 폴더(optional-platforms)가 같은 높이로
놓여, 무엇이 이 애플리케이션의 계층인지 폴더만으로 안 보인다.
src/config/에는 빌드 전체 설정과 기능 하나가 주인인 데이터(jpa,
messaging, mongodb)가 섞여 있다.
고른 방법(소유자 결정 2026-11-07, 설계 가-1):
- git mv로 src/platforms/{messaging,grpc,grpc-advanced,optional-build}.
registry source_path 28행만 바꾸고 Gradle 경로(:messaging:*, :grpc:*)는
그대로다. optional 빌드의 이름(optional-platforms)도 그대로다.
- optional 빌드가 한 단계 깊어져, build-logic이 "optional 빌드의 부모 =
주 빌드"로 가정한 네 곳(registry settings, ArchitecturePlugin, 테스트
이미지 catalog, checkstyle·spotbugs 설정)을 MainBuild(위로 올라가며
registry·설정 파일을 찾음)로 바꾼다.
- settings.gradle·build.gradle의 상대 경로, workflow의 -p 값과 경로,
buf 작업 폴더를 고친다. buf breaking은 이동 전 baseline에서도 옛
경로로 비교해 이동 PR에서 건너뛰지 않는다.
- config/jpa, config/messaging, config/mongodb의 데이터를 주인 leaf의
release/로 옮기고 읽는 빌드 줄·테스트·스크립트·문서를 고친다.
- 루트 CLAUDE.md 5절에 최상위 폴더 지도를 한 줄로 적는다.
버린 대안: Gradle 루트를 저장소 루트로(가-3, CI 재편 때 다시 봄),
application-* 묶기(가-2, 파생 서비스 충돌이 큼).
위험·한계: Gradle 문서의 "이름 = 위치" 권고와 한 단계 어긋난다
(:messaging:x가 platforms/messaging/x). 옮긴 폴더를 고쳐 쓰던 파생
서비스는 이름 바뀜 충돌이 날 수 있다(B-52). docs/capability-status.md
「제거된 코드」 표와 docs/work/evidence.md의 옛 경로는 이력이라 두었다.
검증(desktop, 트리 2b3354a4, ~/t1-layout-logs/):
- ./gradlew :ci :verifyDependencyLocks --warning-mode=fail --continue
첫 실행 rc=1: MessagingAuthorityContractTest가 src/messaging을 찾아 실패
→ 경로를 고침. 두 번째 rc=1: messaging-policy
MessagingAdmissionControllerTest.aWaitingCallerIsAdmittedOnceAPermitIsReturned
(2초 대기 경쟁, 부하 7.3에서 한 번 실패, 코드 변경 없는 leaf) → --rerun
3회 모두 통과. 세 번째 rc=0
- -p platforms/optional-build ci rc=0, 두 빌드의 verifyStrictLaneStages
--dry-run rc=0, -p build-logic check rc=0
- :app-bootstrap:documentContractTest
:adapter:outbound:persistence-mongo:mongoDocumentContractTest rc=0
- ./gradlew projects(주 빌드)와 optional 빌드 projects의 프로젝트 목록이
이동 전 트리와 같다(Gradle 경로 불변)
- check-work-docs.py, 상대 링크 검사 rc=0
Refs: design-docs repo-structure/README.md 3.1, repo-structure/01-backend-layout.md 6.1
BREAKING CHANGE: src/messaging·src/grpc·src/grpc-advanced·src/optional-platforms가 src/platforms/ 아래로, src/config/{jpa,messaging,mongodb}가 주인 leaf의 release/로 옮겨졌다. optional 빌드는 -p platforms/optional-build로 부른다. docs/upgrade/2026-11-maturity-review.md B-52.
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
plugins {
|
||||
id 'ca.platform-module'
|
||||
}
|
||||
|
||||
dependencies {
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
# This is a Gradle generated file for dependency locking.
|
||||
# Manual edits can break the build and are not advised.
|
||||
# This file is expected to be part of source control.
|
||||
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
|
||||
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
|
||||
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
|
||||
com.github.spotbugs:spotbugs:4.10.2=spotbugs
|
||||
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
|
||||
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
|
||||
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
|
||||
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
|
||||
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
|
||||
com.google.code.gson:gson:2.13.2=spotbugs
|
||||
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
|
||||
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
|
||||
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
|
||||
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
|
||||
com.google.guava:guava:33.6.0-jre=checkstyle
|
||||
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
|
||||
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
|
||||
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
|
||||
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
|
||||
commons-beanutils:commons-beanutils:1.11.0=checkstyle
|
||||
commons-collections:commons-collections:3.2.2=checkstyle
|
||||
commons-io:commons-io:2.21.0=spotbugs
|
||||
info.picocli:picocli:4.7.7=checkstyle
|
||||
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
|
||||
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
|
||||
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
|
||||
jaxen:jaxen:2.0.6=spotbugs
|
||||
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
|
||||
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
|
||||
org.antlr:antlr4-runtime:4.13.2=checkstyle
|
||||
org.apache.bcel:bcel:6.12.0=spotbugs
|
||||
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
|
||||
org.apache.commons:commons-text:1.15.0=spotbugs
|
||||
org.apache.commons:commons-text:1.3=checkstyle
|
||||
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
|
||||
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
|
||||
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs
|
||||
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
|
||||
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
|
||||
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
|
||||
org.apache.xbean:xbean-reflect:3.7=checkstyle
|
||||
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
|
||||
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
|
||||
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
|
||||
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
|
||||
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
|
||||
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
|
||||
org.dom4j:dom4j:2.2.0=spotbugs
|
||||
org.javassist:javassist:3.28.0-GA=checkstyle
|
||||
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath
|
||||
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
|
||||
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
|
||||
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
|
||||
org.junit:junit-bom:6.1.0=spotbugs
|
||||
org.mockito:mockito-core:5.20.0=mockitoAgent
|
||||
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
|
||||
org.ow2.asm:asm-analysis:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-commons:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-tree:9.10.1=spotbugs
|
||||
org.ow2.asm:asm-util:9.10.1=spotbugs
|
||||
org.ow2.asm:asm:9.10.1=spotbugs
|
||||
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
|
||||
org.reflections:reflections:0.10.2=checkstyle
|
||||
org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j
|
||||
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
|
||||
org.slf4j:slf4j-simple:2.0.18=checkstyle
|
||||
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
|
||||
empty=compileClasspath,runtimeClasspath
|
||||
+18
@@ -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");
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
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;
|
||||
|
||||
/** {@code type/subtype} with the optional parameters RFC 9110 allows. */
|
||||
private static final java.util.regex.Pattern MEDIA_TYPE =
|
||||
java.util.regex.Pattern.compile(
|
||||
"[A-Za-z0-9][A-Za-z0-9!#$%&'*+.^_`|~-]*"
|
||||
+ "/[A-Za-z0-9][A-Za-z0-9!#$%&'*+.^_`|~-]*"
|
||||
+ "(;\\s*[A-Za-z0-9!#$%&'*+.^_`|~-]+=[^;\\s]+)*");
|
||||
|
||||
/** 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");
|
||||
}
|
||||
// A media type, not merely a string containing a slash. `a/b/c`, `/json` and `text/` all
|
||||
// passed the old check and are all rejected by a broker or a codec registry later, with an
|
||||
// error that names the message rather than the configuration that produced it.
|
||||
if (!MEDIA_TYPE.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException(
|
||||
"contentType must be a type/subtype media type: '" + value + '\'');
|
||||
}
|
||||
value = value.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package dev.caskeleton.messaging.api;
|
||||
|
||||
/**
|
||||
* Workflow-scoped correlation value shared by every message of one business flow.
|
||||
*
|
||||
* <p>This value is copied onto every message of a flow and onto the header set of every broker the
|
||||
* flow touches, so it is bounded in {@link WireSafeText UTF-8 bytes} rather than in Java
|
||||
* characters: the previous 160-character bound admitted a 640-byte value, which a broker with a
|
||||
* byte-counted header budget rejects at publish time, mid-flow, on a message the caller cannot
|
||||
* resend under a different identity.
|
||||
*
|
||||
* @param value the correlation value, 1 to 160 UTF-8 bytes and free of control characters
|
||||
*/
|
||||
public record CorrelationId(String value) {
|
||||
|
||||
private static final int MAX_BYTES = 160;
|
||||
|
||||
public CorrelationId {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException("correlationId must not be blank");
|
||||
}
|
||||
WireSafeText.require(value, "a correlation id", MAX_BYTES);
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
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");
|
||||
// Both keys are routing input the caller chooses, and both used to be unbounded strings. A
|
||||
// partition key is hashed by the broker, so an unbounded one is a cost rather than a
|
||||
// correctness problem; an ordering key is carried on the wire by several bindings, so a
|
||||
// control character in it is the same injection primitive as in a header. The bound is the
|
||||
// smallest one every targeted broker accepts.
|
||||
partitionKey.ifPresent(key -> WireSafeText.require(key, "a partition key", MAX_KEY_BYTES));
|
||||
orderingKey.ifPresent(key -> WireSafeText.require(key, "an ordering key", MAX_KEY_BYTES));
|
||||
}
|
||||
|
||||
/** The routing-key bound every targeted broker accepts. */
|
||||
private static final int MAX_KEY_BYTES = 1024;
|
||||
|
||||
/**
|
||||
* 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 bound to a tenant.
|
||||
*
|
||||
* @param tenant the tenant this message belongs to
|
||||
* @return an envelope with identical identity and payload
|
||||
*/
|
||||
public MessageEnvelope<T> withTenant(TenantContext tenant) {
|
||||
return new MessageEnvelope<>(
|
||||
messageId,
|
||||
messageType,
|
||||
schemaVersion,
|
||||
producedAt,
|
||||
occurredAt,
|
||||
producer,
|
||||
correlationId,
|
||||
causationId,
|
||||
contentType,
|
||||
partitionKey,
|
||||
orderingKey,
|
||||
Optional.of(Objects.requireNonNull(tenant, "tenant must not be null")),
|
||||
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);
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
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) {
|
||||
|
||||
/** The UUID version this identity is documented to carry. */
|
||||
private static final int VERSION_7 = 7;
|
||||
|
||||
public MessageId {
|
||||
Objects.requireNonNull(value, "messageId value must not be null");
|
||||
// The type says UUIDv7 and the constructor accepted any UUID, including v4 and the nil UUID.
|
||||
// Version 7 is what makes the identity time-ordered, which is what the outbox index and every
|
||||
// "oldest first" claim depend on; a v4 stored in the same column silently defeats both.
|
||||
if (value.version() != VERSION_7) {
|
||||
throw new IllegalArgumentException(
|
||||
"a message identity is UUIDv7 (time-ordered); this is version " + value.version());
|
||||
}
|
||||
if (value.variant() != 2) {
|
||||
throw new IllegalArgumentException("a message identity must use the RFC 4122 variant");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mints a new logical message identity.
|
||||
*
|
||||
* @return a fresh time-ordered identity
|
||||
*/
|
||||
public static MessageId newId() {
|
||||
return new MessageId(UuidV7.next());
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
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 UTF-8 bytes and free of control characters
|
||||
*/
|
||||
public record MessageType(String value) {
|
||||
|
||||
private static final int MAX_BYTES = 240;
|
||||
|
||||
public MessageType {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException("messageType must not be blank");
|
||||
}
|
||||
WireSafeText.require(value, "a message type", MAX_BYTES);
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
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 UTF-8 bytes and free of control characters
|
||||
*/
|
||||
public record ProducerId(String value) {
|
||||
|
||||
private static final int MAX_BYTES = 120;
|
||||
|
||||
public ProducerId {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException("producerId must not be blank");
|
||||
}
|
||||
WireSafeText.require(value, "a producer id", MAX_BYTES);
|
||||
}
|
||||
}
|
||||
+15
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package dev.caskeleton.messaging.api;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* <p>The three values used to be checked for non-nullness and nothing more, which made this record
|
||||
* a general-purpose string carrier wearing the name of a standard. Anything accepted here is
|
||||
* written to the {@code traceparent}, {@code tracestate} and {@code baggage} headers of every
|
||||
* broker the message touches, so an unvalidated value is both a header-injection vector and a
|
||||
* silent trace break: a collector that cannot parse {@code traceparent} drops the span rather than
|
||||
* reporting a bad value, and the trace disappears at exactly the hop being investigated.
|
||||
*
|
||||
* @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) {
|
||||
|
||||
/**
|
||||
* {@code version-traceid-spanid-flags}, all lowercase hex, per the W3C Trace Context grammar.
|
||||
*
|
||||
* <p>Uppercase hex is refused rather than folded: the standard defines the field as lowercase,
|
||||
* and a receiver comparing trace IDs as strings — which collectors do — would treat the two cases
|
||||
* as two different traces.
|
||||
*/
|
||||
private static final Pattern TRACEPARENT =
|
||||
Pattern.compile("[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}");
|
||||
|
||||
private static final String ALL_ZERO_TRACE_ID = "0".repeat(32);
|
||||
|
||||
private static final String ALL_ZERO_SPAN_ID = "0".repeat(16);
|
||||
|
||||
/** {@code key=value} or {@code tenant@vendor=value}, per the standard's list-member grammar. */
|
||||
private static final Pattern TRACESTATE_MEMBER =
|
||||
Pattern.compile(
|
||||
"[a-z0-9][_\\-*/a-z0-9]{0,255}(@[a-z0-9][_\\-*/a-z0-9]{0,13})?=[\\x20-\\x7E&&[^,=]]{0,255}");
|
||||
|
||||
/**
|
||||
* The standard's bounds: at most 32 list members, and a field a receiver is allowed to truncate.
|
||||
*/
|
||||
private static final int MAX_TRACESTATE_MEMBERS = 32;
|
||||
|
||||
private static final int MAX_TRACESTATE_BYTES = 512;
|
||||
|
||||
/** W3C Baggage bounds: 8192 bytes total across at most 64 members. */
|
||||
private static final int MAX_BAGGAGE_BYTES = 8192;
|
||||
|
||||
private static final int MAX_BAGGAGE_MEMBERS = 64;
|
||||
|
||||
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");
|
||||
traceparent.ifPresent(TraceContext::requireValidTraceparent);
|
||||
tracestate.ifPresent(TraceContext::requireValidTracestate);
|
||||
baggage.ifPresent(TraceContext::requireValidBaggage);
|
||||
if (tracestate.isPresent() && traceparent.isEmpty()) {
|
||||
// A tracestate without a traceparent is vendor state belonging to no trace. Propagating it
|
||||
// hands the next hop a key it will attribute to whatever trace that hop starts.
|
||||
throw new IllegalArgumentException("tracestate must not be present without a traceparent");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireValidTraceparent(String value) {
|
||||
if (!TRACEPARENT.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException(
|
||||
"traceparent must be version-traceid-spanid-flags in lowercase hex: '" + value + '\'');
|
||||
}
|
||||
String version = value.substring(0, 2);
|
||||
if ("ff".equals(version)) {
|
||||
// The standard reserves ff and requires a receiver to reject it, rather than treat it as a
|
||||
// future version to be forwarded.
|
||||
throw new IllegalArgumentException("traceparent version ff is invalid");
|
||||
}
|
||||
String traceId = value.substring(3, 35);
|
||||
if (ALL_ZERO_TRACE_ID.equals(traceId)) {
|
||||
throw new IllegalArgumentException("traceparent carries an all-zero trace id");
|
||||
}
|
||||
String spanId = value.substring(36, 52);
|
||||
if (ALL_ZERO_SPAN_ID.equals(spanId)) {
|
||||
throw new IllegalArgumentException("traceparent carries an all-zero parent span id");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireValidTracestate(String value) {
|
||||
int bytes = value.getBytes(StandardCharsets.UTF_8).length;
|
||||
if (bytes > MAX_TRACESTATE_BYTES) {
|
||||
throw new IllegalArgumentException("tracestate exceeds 512 bytes: " + bytes);
|
||||
}
|
||||
String[] members = value.split(",", -1);
|
||||
if (members.length > MAX_TRACESTATE_MEMBERS) {
|
||||
throw new IllegalArgumentException(
|
||||
"tracestate carries more than 32 list members: " + members.length);
|
||||
}
|
||||
for (String member : members) {
|
||||
String trimmed = member.strip();
|
||||
if (trimmed.isEmpty()) {
|
||||
// The grammar permits empty members for forward compatibility; nothing is propagated for
|
||||
// them, so they are dropped by the receiver rather than being an error here.
|
||||
continue;
|
||||
}
|
||||
if (!TRACESTATE_MEMBER.matcher(trimmed).matches()) {
|
||||
throw new IllegalArgumentException("tracestate member is not valid: '" + trimmed + '\'');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireValidBaggage(String value) {
|
||||
int bytes = value.getBytes(StandardCharsets.UTF_8).length;
|
||||
if (bytes > MAX_BAGGAGE_BYTES) {
|
||||
throw new IllegalArgumentException("baggage exceeds 8192 bytes: " + bytes);
|
||||
}
|
||||
WireSafeText.requireNoControls(value, "baggage");
|
||||
String[] members = value.split(",", -1);
|
||||
if (members.length > MAX_BAGGAGE_MEMBERS) {
|
||||
throw new IllegalArgumentException("baggage carries more than 64 members: " + members.length);
|
||||
}
|
||||
for (String member : members) {
|
||||
String trimmed = member.strip();
|
||||
int equals = trimmed.indexOf('=');
|
||||
if (equals <= 0 || equals == trimmed.length() - 1) {
|
||||
throw new IllegalArgumentException("baggage member must be key=value: '" + trimmed + '\'');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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());
|
||||
}
|
||||
}
|
||||
+62
@@ -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;
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package dev.caskeleton.messaging.api;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* The one place that decides which text may reach a broker.
|
||||
*
|
||||
* <p>Every wire-facing value used to bound itself in Java {@code char}s and check nothing else. A
|
||||
* {@code char} count bounds nothing on a wire: a 240-character string is up to 960 UTF-8 bytes, so
|
||||
* a "240 character" limit is a 960-byte limit against a broker that counts bytes. And a control
|
||||
* character passes a length check untouched — CR and LF split records on line-oriented protocols,
|
||||
* NUL truncates them in C string handling inside a broker, and DEL is stripped by some
|
||||
* intermediaries and preserved by others. A value that survives one broker and corrupts the next is
|
||||
* worse than a rejected one.
|
||||
*
|
||||
* <p>The rule is refused rather than sanitised on purpose. Silently stripping a CR turns a caller's
|
||||
* two-line value into a one-line value that no longer means what they wrote, and the caller never
|
||||
* learns; the broker downstream cannot tell the difference between that and a legitimate value.
|
||||
*
|
||||
* <p>Each copy of this check that lived in its own record was one more place for the rule to drift.
|
||||
*/
|
||||
public final class WireSafeText {
|
||||
|
||||
private WireSafeText() {}
|
||||
|
||||
/**
|
||||
* Refuses text that no broker should be asked to carry.
|
||||
*
|
||||
* <p>Horizontal tab is refused along with the rest of the C0 range. It is legal in an HTTP field
|
||||
* value, and that is exactly the problem: a header carried over a line-folding binding and the
|
||||
* same header carried over a length-prefixed one disagree about whether a tab ends the value.
|
||||
* Nothing in this platform needs a tab in an identifier or a header.
|
||||
*
|
||||
* @param value the text to check
|
||||
* @param what a noun phrase naming the value, used in the failure message
|
||||
* @param maxBytes the inclusive UTF-8 byte bound
|
||||
* @throws IllegalArgumentException when the text carries a control character or exceeds the bound
|
||||
*/
|
||||
public static void require(String value, String what, int maxBytes) {
|
||||
requireNoControls(value, what);
|
||||
int bytes = value.getBytes(StandardCharsets.UTF_8).length;
|
||||
if (bytes > maxBytes) {
|
||||
throw new IllegalArgumentException(
|
||||
what + " exceeds " + maxBytes + " UTF-8 bytes: " + bytes + " bytes");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses control characters without applying a size bound.
|
||||
*
|
||||
* @param value the text to check
|
||||
* @param what a noun phrase naming the value, used in the failure message
|
||||
* @throws IllegalArgumentException when the text carries a control character
|
||||
*/
|
||||
public static void requireNoControls(String value, String what) {
|
||||
for (int index = 0; index < value.length(); index++) {
|
||||
char character = value.charAt(index);
|
||||
if (character < 0x20 || character == 0x7F) {
|
||||
throw new IllegalArgumentException(
|
||||
"%s must not contain control characters (found U+%04X at index %d)"
|
||||
.formatted(what, (int) character, index));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+36
@@ -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);
|
||||
}
|
||||
}
|
||||
+18
@@ -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
|
||||
}
|
||||
+46
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -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
|
||||
}
|
||||
+60
@@ -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();
|
||||
}
|
||||
}
|
||||
+22
@@ -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");
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package dev.caskeleton.messaging.api.delivery;
|
||||
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/**
|
||||
* The one consume contract, 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 consume a
|
||||
* destination whose profile declares {@code INBOX_TRANSACTIONAL}, where the platform runs the
|
||||
* handler inside the inbox reservation's transaction.
|
||||
*
|
||||
* <p>Registering an implementation as a bean is what turns consumption on: the broker starter opens
|
||||
* a consumer for every destination at least one handler names. There is no second, batch or manual
|
||||
* settlement contract; the platform settles, after the handler has answered.
|
||||
*
|
||||
* @param <T> the payload type
|
||||
*/
|
||||
public interface MessageHandler<T> {
|
||||
|
||||
/**
|
||||
* The destination, message type and payload type this handler consumes.
|
||||
*
|
||||
* <p>A destination may carry several message types; each type has at most one handler.
|
||||
*
|
||||
* @return what this handler consumes
|
||||
*/
|
||||
MessageDestination<T> destination();
|
||||
|
||||
/**
|
||||
* The schema versions of {@link #destination()}'s message type that its payload class reads.
|
||||
*
|
||||
* <p>This declaration is the consumer's whole registration. The platform decodes a delivery only
|
||||
* against a contract — message type and schema version — it knows the payload class for, and it
|
||||
* builds that list from the handler beans: each version here, with the destination's message
|
||||
* type, decodes into the destination's payload class. A service writes no registration code of
|
||||
* its own, so a handler cannot exist while its messages are dead-lettered as undecodable for want
|
||||
* of one.
|
||||
*
|
||||
* <p>A version the handler does not name is still refused ({@code SCHEMA_VERSION_NOT_REGISTERED})
|
||||
* rather than decoded into a class written for another version. A handler that reads a second
|
||||
* version says so here when the producer starts sending it.
|
||||
*
|
||||
* @return the versions this handler reads; version 1 unless it declares otherwise
|
||||
*/
|
||||
default Set<SchemaVersion> schemaVersions() {
|
||||
return Set.of(new SchemaVersion(1));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
+23
@@ -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
|
||||
}
|
||||
+20
@@ -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
|
||||
}
|
||||
+26
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -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
|
||||
}
|
||||
+24
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -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");
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package dev.caskeleton.messaging.api.destination;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.EnumSet;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* <p>A set of named capabilities rather than a row of positional booleans. The record used to take
|
||||
* twelve booleans in a fixed order, and an adapter declared itself with {@code new
|
||||
* MessagingCapabilities(true, true, …, false, true)} — a line where swapping two arguments changes
|
||||
* a guarantee and still compiles. Only the capabilities the platform reads are named: a flag
|
||||
* nothing consults is a promise nobody checks.
|
||||
*
|
||||
* @param supported the capabilities the adapter can prove
|
||||
*/
|
||||
public record MessagingCapabilities(Set<Capability> supported) {
|
||||
|
||||
/** One capability the platform consults before relying on it. */
|
||||
public enum Capability {
|
||||
|
||||
/** The destination preserves order inside an ordering unit; required by pause-and-retry. */
|
||||
ORDERED_STREAM,
|
||||
|
||||
/** Delivery can be scheduled for a future instant; required by broker-delayed retry. */
|
||||
DELAYED_DELIVERY,
|
||||
|
||||
/** The broker suppresses duplicate publishes of a stable id; required by publish dedup. */
|
||||
DEDUPLICATED_PUBLISH
|
||||
}
|
||||
|
||||
public MessagingCapabilities {
|
||||
Objects.requireNonNull(supported, "supported must not be null");
|
||||
supported =
|
||||
Collections.unmodifiableSet(
|
||||
supported.isEmpty() ? EnumSet.noneOf(Capability.class) : EnumSet.copyOf(supported));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a capability set with nothing enabled.
|
||||
*
|
||||
* @return the empty capability set
|
||||
*/
|
||||
public static MessagingCapabilities none() {
|
||||
return new MessagingCapabilities(EnumSet.noneOf(Capability.class));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a capability set holding exactly the named capabilities.
|
||||
*
|
||||
* @param first the first capability
|
||||
* @param rest the remaining capabilities
|
||||
* @return the capability set
|
||||
*/
|
||||
public static MessagingCapabilities of(Capability first, Capability... rest) {
|
||||
return new MessagingCapabilities(EnumSet.of(first, rest));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the adapter can prove a capability.
|
||||
*
|
||||
* @param capability the capability to look up
|
||||
* @return true when it is supported
|
||||
*/
|
||||
public boolean supports(Capability capability) {
|
||||
return supported.contains(Objects.requireNonNull(capability, "capability must not be null"));
|
||||
}
|
||||
}
|
||||
+40
@@ -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
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
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.
|
||||
*
|
||||
* <p>A default, not a rule every descriptor follows. A publish rejection may carry {@code
|
||||
* retryable = true} with an authentication or authorization category: the broker did not store
|
||||
* the record, and a credential being rotated or an ACL deployed after the application refuses
|
||||
* every publish for a few minutes and then stops (the Kafka publish classifier). The
|
||||
* consumer-side retry engine requires this default as well as the flag unless its policy names
|
||||
* the category, so redelivery of an unauthorised message is still not retried; only a publisher
|
||||
* that reads {@link #retryable()} sees the difference.
|
||||
*
|
||||
* @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;
|
||||
};
|
||||
}
|
||||
}
|
||||
+49
@@ -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);
|
||||
}
|
||||
}
|
||||
+40
@@ -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);
|
||||
}
|
||||
}
|
||||
+54
@@ -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);
|
||||
}
|
||||
}
|
||||
+49
@@ -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);
|
||||
}
|
||||
}
|
||||
+49
@@ -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);
|
||||
}
|
||||
}
|
||||
+54
@@ -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);
|
||||
}
|
||||
}
|
||||
+49
@@ -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);
|
||||
}
|
||||
}
|
||||
+49
@@ -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);
|
||||
}
|
||||
}
|
||||
+56
@@ -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);
|
||||
}
|
||||
}
|
||||
+55
@@ -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);
|
||||
}
|
||||
}
|
||||
+66
@@ -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();
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package dev.caskeleton.messaging.api.header;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Splits the reserved namespace into the part an envelope field already owns and the part that only
|
||||
* a header can carry.
|
||||
*
|
||||
* <p>{@link ReservedHeaders} answers one question — does the platform own this name — and every
|
||||
* adapter that asked it treated the whole namespace as forgeable content. That is right for {@code
|
||||
* msg.id} and wrong for {@code msg.retry-attempt}: the first restates a value the envelope already
|
||||
* holds, so a header claiming it can only overwrite the canonical one, while the second has no
|
||||
* envelope field at all and exists precisely to survive a hop through a broker. Refusing both is
|
||||
* how a retry re-publish becomes an error, and dropping both on the way back is how an attempt
|
||||
* counter silently restarts at one and a retry budget stops capping anything.
|
||||
*
|
||||
* <p>The split is derived from the envelope's own shape rather than listed by hand per adapter, so
|
||||
* Kafka and RabbitMQ cannot disagree about which headers are identity and which are bookkeeping — a
|
||||
* disagreement that would make the same message mean different things on two brokers.
|
||||
*/
|
||||
public final class CanonicalEnvelopeHeaders {
|
||||
|
||||
/**
|
||||
* Reserved names that restate a value the envelope already carries in a field.
|
||||
*
|
||||
* <p>Every one of these is written by the adapter from an envelope field on the way out and read
|
||||
* back into that field on the way in. A copy of it inside the header map is therefore never the
|
||||
* source of truth, only a way to disagree with it.
|
||||
*/
|
||||
private static final Set<String> ENVELOPE_FIELDS =
|
||||
Set.of(
|
||||
ReservedHeaders.MESSAGE_ID,
|
||||
ReservedHeaders.MESSAGE_TYPE,
|
||||
ReservedHeaders.SCHEMA_VERSION,
|
||||
ReservedHeaders.PRODUCER,
|
||||
ReservedHeaders.PRODUCED_AT,
|
||||
ReservedHeaders.OCCURRED_AT,
|
||||
ReservedHeaders.CORRELATION_ID,
|
||||
ReservedHeaders.CAUSATION_ID,
|
||||
ReservedHeaders.CONTENT_TYPE,
|
||||
ReservedHeaders.PARTITION_KEY,
|
||||
ReservedHeaders.ORDERING_KEY,
|
||||
ReservedHeaders.TENANT,
|
||||
ReservedHeaders.TRACEPARENT,
|
||||
ReservedHeaders.TRACESTATE,
|
||||
ReservedHeaders.BAGGAGE);
|
||||
|
||||
private CanonicalEnvelopeHeaders() {}
|
||||
|
||||
/**
|
||||
* Reports whether a header name restates an envelope field.
|
||||
*
|
||||
* @param name the header name in any case
|
||||
* @return true when the envelope already carries this value in a field of its own
|
||||
*/
|
||||
public static boolean restatesEnvelopeField(String name) {
|
||||
return name != null && ENVELOPE_FIELDS.contains(name.toLowerCase(Locale.ROOT));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether a header name is platform bookkeeping that must travel in the header map.
|
||||
*
|
||||
* @param name the header name in any case
|
||||
* @return true for a reserved name with no envelope field behind it
|
||||
*/
|
||||
public static boolean isPlatformBookkeeping(String name) {
|
||||
return ReservedHeaders.isReserved(name) && !restatesEnvelopeField(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the reserved names an envelope field owns.
|
||||
*
|
||||
* @return an immutable set of lowercase names
|
||||
*/
|
||||
public static Set<String> envelopeFieldNames() {
|
||||
return ENVELOPE_FIELDS;
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
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;
|
||||
|
||||
/**
|
||||
* The one grammar a header name may use.
|
||||
*
|
||||
* <p>The previous check was "not blank, at most 128 bytes", which accepted a name containing CR,
|
||||
* LF, NUL, a colon or leading whitespace. Those are not cosmetic: a newline in a header name is a
|
||||
* header-injection primitive on any line-oriented protocol, a NUL truncates the name in C string
|
||||
* handling inside a broker, and a colon is the field separator in several wire formats. A name
|
||||
* that survives one broker and corrupts the next is worse than a rejected one.
|
||||
*
|
||||
* <p>The character set is the HTTP token set, which every broker this platform targets accepts
|
||||
* verbatim.
|
||||
*/
|
||||
private static final java.util.regex.Pattern TOKEN =
|
||||
java.util.regex.Pattern.compile("[a-zA-Z0-9!#$%&'*+._|~-]+");
|
||||
|
||||
public HeaderName {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException("header name must not be blank");
|
||||
}
|
||||
if (!value.equals(value.strip())) {
|
||||
// Trimming would mean `Authorization ` and `Authorization` are the same name to the
|
||||
// denylist and different names on the wire, which is precisely how the check was bypassed.
|
||||
throw new IllegalArgumentException(
|
||||
"header name must not have leading or trailing whitespace: '" + value + '\'');
|
||||
}
|
||||
if (!TOKEN.matcher(value).matches()) {
|
||||
throw new IllegalArgumentException(
|
||||
"header name must be an ASCII token; control characters, spaces, colons and non-ASCII"
|
||||
+ " are refused because a broker that accepts one may truncate or split on it");
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.caskeleton.messaging.api.header;
|
||||
|
||||
import dev.caskeleton.messaging.api.WireSafeText;
|
||||
|
||||
/**
|
||||
* Value of a single message header.
|
||||
*
|
||||
* <p>The bound used to be the only rule, so a value containing CR, LF or NUL reached the broker
|
||||
* intact. On a line-oriented binding a CRLF inside a value ends the header and starts a new one the
|
||||
* caller wrote — the same header-injection primitive as in HTTP, with the broker's own control
|
||||
* headers as the target. A NUL truncates the value inside a broker that hands it to C string
|
||||
* handling, so a subscriber receives a prefix of what was published and cannot tell.
|
||||
*
|
||||
* @param value the header value, at most 4096 UTF-8 bytes and free of control characters
|
||||
*/
|
||||
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");
|
||||
}
|
||||
WireSafeText.require(value, "a header value", MAX_BYTES);
|
||||
}
|
||||
}
|
||||
+211
@@ -0,0 +1,211 @@
|
||||
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");
|
||||
|
||||
/**
|
||||
* Words that make a header name a credential regardless of what surrounds them.
|
||||
*
|
||||
* <p>Exact-name matching only refuses the spellings someone thought of. {@code x-api-key}, {@code
|
||||
* auth-token} and {@code db_password} are the same credential leak as {@code authorization} and
|
||||
* none of them was on the list. Matching whole segments rather than substrings is what keeps
|
||||
* {@code tokenizer-version} or {@code secretariat-id} from being refused for containing the
|
||||
* letters of a secret.
|
||||
*/
|
||||
private static final Set<String> SECRET_SEGMENTS =
|
||||
Set.of(
|
||||
"password",
|
||||
"passwd",
|
||||
"secret",
|
||||
"token",
|
||||
"credential",
|
||||
"credentials",
|
||||
"apikey",
|
||||
"authorization",
|
||||
"cookie",
|
||||
"signature");
|
||||
|
||||
private static final java.util.regex.Pattern SEGMENT_SEPARATOR =
|
||||
java.util.regex.Pattern.compile("[._\\-]+");
|
||||
|
||||
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 (carriesACredential(normalized)) {
|
||||
// The name is reported and the value never is: an error message is written to a log that
|
||||
// is exactly as readable as the broker storage this check exists to keep the value out of.
|
||||
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));
|
||||
}
|
||||
|
||||
private static boolean carriesACredential(String normalized) {
|
||||
if (SECRET_NAMES.contains(normalized)) {
|
||||
return true;
|
||||
}
|
||||
String[] segments = SEGMENT_SEPARATOR.split(normalized, -1);
|
||||
for (int index = 0; index < segments.length; index++) {
|
||||
if (SECRET_SEGMENTS.contains(segments[index])) {
|
||||
return true;
|
||||
}
|
||||
// Adjacent segments are also tested joined, because the same word is written both ways:
|
||||
// `api_key` is one segment to a reader and two to a splitter, and `x-api-key` is two of
|
||||
// three. Joining only neighbouring pairs is what keeps `routing-key` accepted.
|
||||
if (index + 1 < segments.length
|
||||
&& SECRET_SEGMENTS.contains(segments[index] + segments[index + 1])) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() + "]";
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
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";
|
||||
|
||||
/**
|
||||
* Bounded tenant identity.
|
||||
*
|
||||
* <p>The envelope carried a tenant and no header name existed for it, so the write side had
|
||||
* nothing to write and the read side rebuilt every consumed message with an empty tenant. A
|
||||
* message published by one tenant and consumed as belonging to none is not a lost label: it is
|
||||
* the field every downstream authorization and data-partitioning decision reads.
|
||||
*/
|
||||
public static final String TENANT = "msg.tenant";
|
||||
|
||||
/** 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,
|
||||
TENANT,
|
||||
REDRIVE_ID,
|
||||
REDRIVE_COUNT,
|
||||
RETRY_ATTEMPT,
|
||||
FIRST_FAILURE_AT,
|
||||
LAST_FAILURE_AT,
|
||||
FAILURE_CATEGORY,
|
||||
FAILURE_CODE,
|
||||
ORIGIN_DESTINATION,
|
||||
TRACEPARENT,
|
||||
TRACESTATE,
|
||||
BAGGAGE);
|
||||
|
||||
private ReservedHeaders() {}
|
||||
|
||||
/**
|
||||
* The namespace the platform owns, whether or not a name in it exists yet.
|
||||
*
|
||||
* <p>The check used to be exact membership of {@link #NAMES}, so {@code msg.anything} that this
|
||||
* release has not defined was an ordinary application header — until a later release defined it,
|
||||
* at which point every application already writing it silently started overwriting envelope
|
||||
* metadata. Owning the prefix means a new platform header is a compatible change.
|
||||
*/
|
||||
private static final String PLATFORM_PREFIX = "msg.";
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
if (name == null) {
|
||||
return false;
|
||||
}
|
||||
String normalized = name.toLowerCase(Locale.ROOT);
|
||||
return NAMES.contains(normalized) || normalized.startsWith(PLATFORM_PREFIX);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns every reserved header name.
|
||||
*
|
||||
* @return an immutable set of lowercase names
|
||||
*/
|
||||
public static Set<String> names() {
|
||||
return NAMES;
|
||||
}
|
||||
}
|
||||
+27
@@ -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();
|
||||
}
|
||||
+20
@@ -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
|
||||
}
|
||||
+26
@@ -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);
|
||||
}
|
||||
+20
@@ -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
|
||||
}
|
||||
+27
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+66
@@ -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);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package dev.caskeleton.messaging.api.publish;
|
||||
|
||||
import dev.caskeleton.messaging.api.destination.ConfirmationRequirement;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Per-call publish options.
|
||||
*
|
||||
* <p>There is no free-form hint map. One existed for a native surface that does not read it, so the
|
||||
* only thing a caller could do with it was pass adapter settings that the publish path refused at
|
||||
* runtime — an escape hatch around destination policy that never opened. A broker-specific option
|
||||
* belongs in that broker's own typed API, where the adapter that honours it can be seen to.
|
||||
*
|
||||
* @param timeout the publish operation deadline
|
||||
* @param confirmation the confirmation this call requires
|
||||
* @param deduplication optional broker-side duplicate suppression
|
||||
*/
|
||||
public record PublishOptions(
|
||||
Duration timeout,
|
||||
ConfirmationRequirement confirmation,
|
||||
Optional<PublishDeduplication> deduplication) {
|
||||
|
||||
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");
|
||||
if (timeout.isNegative() || timeout.isZero()) {
|
||||
throw new IllegalArgumentException("publish timeout must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the M1 default: five second timeout, replication evidence.
|
||||
*
|
||||
* @return the default options
|
||||
*/
|
||||
public static PublishOptions defaults() {
|
||||
return new PublishOptions(
|
||||
DEFAULT_TIMEOUT, ConfirmationRequirement.REPLICATION_OR_PERSISTENCE_ACK, Optional.empty());
|
||||
}
|
||||
}
|
||||
+40
@@ -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());
|
||||
}
|
||||
}
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
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 every combination that would let a caller read a stronger guarantee
|
||||
* than was actually obtained, and every one that contradicts itself: a rejection the broker
|
||||
* acknowledged, a confirmation that does not know whether it routed, an ambiguous outcome the
|
||||
* broker routed, a broker coordinate for bytes that never left. 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.
|
||||
*
|
||||
* <p>Validating here rather than trusting call sites is deliberate: the record is public, every
|
||||
* adapter builds one, and a contradiction assembled in an adapter is only ever read much later, by
|
||||
* an operator deciding whether to re-publish.
|
||||
*
|
||||
* @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");
|
||||
}
|
||||
if (completion == PublishCompletion.REJECTED && evidence.brokerAccepted()) {
|
||||
// A broker that acknowledged the message did not reject it. Left representable, this is the
|
||||
// combination that turns a delivered message into one the caller re-publishes as if it had
|
||||
// never been sent.
|
||||
throw new IllegalArgumentException("rejected publish cannot claim broker acceptance");
|
||||
}
|
||||
if (completion == PublishCompletion.CONFIRMED && routingOutcome == RoutingOutcome.UNKNOWN) {
|
||||
// The confirmation came from the broker, and the same response says whether it routed. A
|
||||
// confirmed publish that does not know is an adapter reporting half of what it was told.
|
||||
throw new IllegalArgumentException("confirmed publish knows whether it routed");
|
||||
}
|
||||
if (completion == PublishCompletion.AMBIGUOUS && routingOutcome == RoutingOutcome.ROUTED) {
|
||||
// Routing is something only the broker can report, and a broker that reported it answered.
|
||||
throw new IllegalArgumentException("a routed publish is not ambiguous");
|
||||
}
|
||||
if (position.isPresent() && evidence.transmission() == TransmissionEvidence.NOT_TRANSMITTED) {
|
||||
// A partition and offset for a message that never left the process: whatever coordinate this
|
||||
// is, it belongs to some other message, and an operator would chase it.
|
||||
throw new IllegalArgumentException("an untransmitted publish has no broker position");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A publish the broker confirmed.
|
||||
*
|
||||
* @param level the confirmation the broker supplied
|
||||
* @param routing whether the broker routed it; a broker with no routing step reports {@link
|
||||
* RoutingOutcome#NOT_APPLICABLE}
|
||||
* @param position the broker coordinate, when the broker reported one
|
||||
* @param elapsed wall-clock time spent
|
||||
* @return the confirmed result
|
||||
*/
|
||||
public static PublishResult confirmed(
|
||||
ConfirmationLevel level,
|
||||
RoutingOutcome routing,
|
||||
Optional<BrokerPosition> position,
|
||||
Duration elapsed) {
|
||||
return new PublishResult(
|
||||
PublishCompletion.CONFIRMED,
|
||||
PublishEvidence.confirmed(level),
|
||||
routing,
|
||||
position,
|
||||
1,
|
||||
elapsed,
|
||||
Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* A publish refused before anything left the process.
|
||||
*
|
||||
* <p>Routing is {@link RoutingOutcome#NOT_APPLICABLE}: nothing reached a broker that could have
|
||||
* routed it.
|
||||
*
|
||||
* @param elapsed wall-clock time spent
|
||||
* @param failure why it was refused
|
||||
* @return the rejected result
|
||||
*/
|
||||
public static PublishResult rejected(Duration elapsed, FailureDescriptor failure) {
|
||||
return new PublishResult(
|
||||
PublishCompletion.REJECTED,
|
||||
PublishEvidence.notTransmitted(),
|
||||
RoutingOutcome.NOT_APPLICABLE,
|
||||
Optional.empty(),
|
||||
1,
|
||||
elapsed,
|
||||
Optional.of(failure));
|
||||
}
|
||||
|
||||
/**
|
||||
* A publish whose fate is unknown: the broker may or may not hold the message.
|
||||
*
|
||||
* @param elapsed wall-clock time spent
|
||||
* @param failure what made the outcome unknowable
|
||||
* @return the ambiguous result
|
||||
*/
|
||||
public static PublishResult ambiguous(Duration elapsed, FailureDescriptor failure) {
|
||||
return new PublishResult(
|
||||
PublishCompletion.AMBIGUOUS,
|
||||
PublishEvidence.ambiguous(),
|
||||
RoutingOutcome.UNKNOWN,
|
||||
Optional.empty(),
|
||||
1,
|
||||
elapsed,
|
||||
Optional.of(failure));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
+23
@@ -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
|
||||
}
|
||||
+14
@@ -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
|
||||
}
|
||||
+14
@@ -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
|
||||
}
|
||||
+66
@@ -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);
|
||||
}
|
||||
}
|
||||
+47
@@ -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());
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.error.MessageTooLargeException;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* A byte sink that refuses the byte after the limit instead of the buffer after the fact.
|
||||
*
|
||||
* <p>Every codec here used to serialize into an unbounded buffer and compare {@code bytes.length}
|
||||
* to the configured maximum afterwards. That makes the maximum a reporting threshold rather than an
|
||||
* allocation bound: a payload whose graph expands to hundreds of megabytes exhausts the heap while
|
||||
* being written, and the check that would have rejected it never runs. Under a broker consumer that
|
||||
* is a process-wide outage caused by one message.
|
||||
*
|
||||
* <p>This sink fails on the write that would cross the limit, so peak allocation is bounded by the
|
||||
* limit itself plus whatever the encoder buffers. The exception is the same {@link
|
||||
* MessageTooLargeException} the after-the-fact check raised, carrying the codec's own error code,
|
||||
* so callers and evidence records see no behavioural difference for payloads that merely exceed the
|
||||
* bound.
|
||||
*
|
||||
* <p>Not thread-safe, and not meant to be: an instance belongs to a single encode call.
|
||||
*/
|
||||
public final class BoundedByteSink extends OutputStream {
|
||||
|
||||
private final int maxBytes;
|
||||
private final String errorCode;
|
||||
private final ByteArrayOutputStream buffer;
|
||||
private int written;
|
||||
|
||||
private BoundedByteSink(int maxBytes, String errorCode) {
|
||||
if (maxBytes < 1) {
|
||||
throw new IllegalArgumentException("maxBytes must be positive");
|
||||
}
|
||||
this.maxBytes = maxBytes;
|
||||
this.errorCode = Objects.requireNonNull(errorCode, "errorCode must not be null");
|
||||
// Sized to the limit only when the limit is small: a 1 GiB bound must not pre-allocate 1 GiB.
|
||||
this.buffer = new ByteArrayOutputStream(Math.min(maxBytes, 8_192));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a sink that refuses to accumulate more than {@code maxBytes}.
|
||||
*
|
||||
* @param maxBytes the inclusive byte limit
|
||||
* @param errorCode the code the codec reports for an oversized payload
|
||||
* @return a bounded sink
|
||||
*/
|
||||
public static BoundedByteSink of(int maxBytes, String errorCode) {
|
||||
return new BoundedByteSink(maxBytes, errorCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(int b) {
|
||||
reserve(1);
|
||||
buffer.write(b);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] bytes, int offset, int length) {
|
||||
Objects.checkFromIndexSize(offset, length, bytes.length);
|
||||
reserve(length);
|
||||
buffer.write(bytes, offset, length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a size the caller can compute before serializing, without consuming the budget.
|
||||
*
|
||||
* <p>Protobuf knows its serialized size exactly, so the whole encode can be refused before the
|
||||
* first byte is written. The subsequent writes are still bounded — this is a cheaper refusal, not
|
||||
* a replacement for the bound.
|
||||
*
|
||||
* @param size the number of bytes the caller is about to produce
|
||||
*/
|
||||
public void requireFits(int size) {
|
||||
if (size < 0) {
|
||||
throw new IllegalArgumentException("size must not be negative");
|
||||
}
|
||||
refuseIfBeyondLimit(size);
|
||||
}
|
||||
|
||||
private void reserve(int size) {
|
||||
refuseIfBeyondLimit(size);
|
||||
written += size;
|
||||
}
|
||||
|
||||
private void refuseIfBeyondLimit(int size) {
|
||||
if (size > maxBytes - written) {
|
||||
throw new MessageTooLargeException(
|
||||
errorCode,
|
||||
("the encoded payload exceeds the %d byte limit; it was refused at byte %d rather than"
|
||||
+ " buffered in full")
|
||||
.formatted(maxBytes, written + size));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes accumulated so far.
|
||||
*
|
||||
* @return a copy of the buffered bytes
|
||||
*/
|
||||
public byte[] toByteArray() {
|
||||
return buffer.toByteArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* How many bytes have been admitted.
|
||||
*
|
||||
* @return the running total
|
||||
*/
|
||||
public int written() {
|
||||
return written;
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* An encoded payload together with the facts needed to decode it again.
|
||||
*
|
||||
* <p>The byte array is defensively copied on both construction and access. These bytes travel
|
||||
* through retry, DLQ, and redrive paths where a shared mutable array would let one stage corrupt
|
||||
* another's copy of the same logical message.
|
||||
*
|
||||
* @param bytes the encoded payload
|
||||
* @param contentType the codec media type
|
||||
* @param schemaReference the schema the payload was written against
|
||||
*/
|
||||
@SuppressWarnings("ArrayRecordComponent")
|
||||
public record EncodedMessage(
|
||||
byte[] bytes, ContentType contentType, Optional<SchemaReference> schemaReference) {
|
||||
|
||||
public EncodedMessage {
|
||||
Objects.requireNonNull(bytes, "encoded bytes must not be null");
|
||||
Objects.requireNonNull(contentType, "contentType must not be null");
|
||||
Objects.requireNonNull(schemaReference, "schemaReference must not be null");
|
||||
bytes = bytes.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a copy of the encoded bytes.
|
||||
*
|
||||
* @return the payload bytes
|
||||
*/
|
||||
@Override
|
||||
public byte[] bytes() {
|
||||
return bytes.clone();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the encoded size without copying.
|
||||
*
|
||||
* @return the payload length in bytes
|
||||
*/
|
||||
public int size() {
|
||||
return bytes.length;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
return other instanceof EncodedMessage message
|
||||
&& Arrays.equals(bytes, message.bytes)
|
||||
&& contentType.equals(message.contentType)
|
||||
&& schemaReference.equals(message.schemaReference);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(Arrays.hashCode(bytes), contentType, schemaReference);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "EncodedMessage[contentType=" + contentType.value() + ", size=" + bytes.length + "]";
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.publish.PublishOptions;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/**
|
||||
* Publishes an envelope whose payload has already been encoded by an authoritative application
|
||||
* contract boundary.
|
||||
*
|
||||
* <p>This is intentionally narrower than the transport SPI. Callers may skip only the codec step;
|
||||
* destination resolution, access policy, admission, runtime leasing, transport normalization and
|
||||
* observation remain owned by the platform's central publisher.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface EncodedMessagePublisher {
|
||||
|
||||
CompletionStage<PublishResult> publishEncoded(
|
||||
MessageDestination<EncodedMessage> destination,
|
||||
MessageEnvelope<EncodedMessage> message,
|
||||
PublishOptions options);
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
|
||||
/**
|
||||
* Encodes and decodes payloads for a single wire format.
|
||||
*
|
||||
* <p>Implementations operate against a closed message-type registry. Accepting an unregistered type
|
||||
* would let a producer introduce a wire contract nothing has reviewed, which is the same class of
|
||||
* problem that makes Java serialization unsupported here.
|
||||
*/
|
||||
public interface MessageCodec {
|
||||
|
||||
/**
|
||||
* Returns the media type this codec produces.
|
||||
*
|
||||
* @return the content type
|
||||
*/
|
||||
ContentType contentType();
|
||||
|
||||
/**
|
||||
* Encodes a payload.
|
||||
*
|
||||
* @param type the catalog message type
|
||||
* @param version the schema revision
|
||||
* @param payload the payload to encode
|
||||
* @return the encoded message
|
||||
*/
|
||||
EncodedMessage encode(MessageType type, SchemaVersion version, Object payload);
|
||||
|
||||
/**
|
||||
* Decodes a payload from raw bytes.
|
||||
*
|
||||
* @param <T> the payload type
|
||||
* @param type the catalog message type
|
||||
* @param version the schema revision
|
||||
* @param encoded the encoded bytes
|
||||
* @param payloadType the expected payload class
|
||||
* @return the decoded payload
|
||||
*/
|
||||
<T> T decode(MessageType type, SchemaVersion version, byte[] encoded, Class<T> payloadType);
|
||||
|
||||
/**
|
||||
* Decodes a payload from an encoded message.
|
||||
*
|
||||
* @param <T> the payload type
|
||||
* @param type the catalog message type
|
||||
* @param version the schema revision
|
||||
* @param encoded the encoded message
|
||||
* @param payloadType the expected payload class
|
||||
* @return the decoded payload
|
||||
*/
|
||||
default <T> T decode(
|
||||
MessageType type, SchemaVersion version, EncodedMessage encoded, Class<T> payloadType) {
|
||||
return decode(type, version, encoded.bytes(), payloadType);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import java.util.Optional;
|
||||
|
||||
/** Resolves the codec for a content type. */
|
||||
public interface MessageCodecRegistry {
|
||||
|
||||
/**
|
||||
* Returns the codec for a content type.
|
||||
*
|
||||
* @param contentType the media type
|
||||
* @return the codec when registered
|
||||
*/
|
||||
Optional<MessageCodec> find(ContentType contentType);
|
||||
|
||||
/**
|
||||
* Returns the Stable default codec.
|
||||
*
|
||||
* <p>The raw bytes codec is never eligible: selecting it by default would silently disable schema
|
||||
* validation for every destination that forgot to declare one.
|
||||
*
|
||||
* @return the default codec
|
||||
*/
|
||||
MessageCodec defaultCodec();
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The identity a codec registry is keyed on: a message type at a specific schema version.
|
||||
*
|
||||
* <p>Keying on the message type alone is what let an unregistered version decode. The version
|
||||
* travels in the envelope and in {@link SchemaReference}, so a consumer receiving {@code
|
||||
* order.created v999} would look up {@code order.created}, find the v1 class or parser, decode
|
||||
* against it, and then keep the v999 label on the result. Nothing failed, and every downstream
|
||||
* compatibility gate and audit record then described a version that was never registered.
|
||||
*
|
||||
* <p>With the version in the key that lookup misses, which is the only honest outcome: the platform
|
||||
* has no contract for that version and must say so rather than guess one.
|
||||
*
|
||||
* @param type the catalog message type
|
||||
* @param version the schema version the contract is registered for
|
||||
*/
|
||||
public record MessageContractKey(MessageType type, SchemaVersion version) {
|
||||
|
||||
/** Validates both components. */
|
||||
public MessageContractKey {
|
||||
Objects.requireNonNull(type, "messageType must not be null");
|
||||
Objects.requireNonNull(version, "schemaVersion must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a key from raw components.
|
||||
*
|
||||
* @param type the catalog message type
|
||||
* @param version the schema version
|
||||
* @return the key
|
||||
*/
|
||||
public static MessageContractKey of(String type, int version) {
|
||||
return new MessageContractKey(new MessageType(type), new SchemaVersion(version));
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the key the way error messages and audit records name a contract.
|
||||
*
|
||||
* @return for example {@code order.created v1}
|
||||
*/
|
||||
public String describe() {
|
||||
return type.value() + " v" + version.value();
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.error.MessageSerializationException;
|
||||
import dev.caskeleton.messaging.api.error.MessageTooLargeException;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The M2 escape hatch for payloads that carry no schema.
|
||||
*
|
||||
* <p>It still enforces the byte limit, and it is deliberately excluded from default codec
|
||||
* selection: schema-free publishing has to be an explicit, auditable choice per destination, never
|
||||
* something a destination falls back to because its codec was misconfigured.
|
||||
*/
|
||||
public final class RawBytesMessageCodec implements MessageCodec {
|
||||
|
||||
/** The default encoded byte limit shared with the Stable codecs. */
|
||||
public static final int DEFAULT_MAX_BYTES = 1_048_576;
|
||||
|
||||
private final int maxBytes;
|
||||
|
||||
/** Creates a codec with the default one mebibyte limit. */
|
||||
public RawBytesMessageCodec() {
|
||||
this(DEFAULT_MAX_BYTES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a codec with an explicit byte limit.
|
||||
*
|
||||
* @param maxBytes the maximum encoded size
|
||||
*/
|
||||
public RawBytesMessageCodec(int maxBytes) {
|
||||
if (maxBytes < 1) {
|
||||
throw new IllegalArgumentException("maxBytes must be positive");
|
||||
}
|
||||
this.maxBytes = maxBytes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ContentType contentType() {
|
||||
return ContentType.OCTET_STREAM;
|
||||
}
|
||||
|
||||
@Override
|
||||
public EncodedMessage encode(MessageType type, SchemaVersion version, Object payload) {
|
||||
Objects.requireNonNull(type, "messageType must not be null");
|
||||
Objects.requireNonNull(version, "schemaVersion must not be null");
|
||||
if (!(payload instanceof byte[] bytes)) {
|
||||
throw new MessageSerializationException(
|
||||
"RAW_BYTES_PAYLOAD_REQUIRED", "raw bytes codec accepts only byte[] payloads");
|
||||
}
|
||||
if (bytes.length > maxBytes) {
|
||||
throw new MessageTooLargeException(
|
||||
"RAW_BYTES_TOO_LARGE", "encoded payload exceeds " + maxBytes + " bytes");
|
||||
}
|
||||
return new EncodedMessage(bytes, ContentType.OCTET_STREAM, Optional.empty());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T decode(
|
||||
MessageType type, SchemaVersion version, byte[] encoded, Class<T> payloadType) {
|
||||
Objects.requireNonNull(encoded, "encoded bytes must not be null");
|
||||
if (!payloadType.equals(byte[].class)) {
|
||||
throw new MessageSerializationException(
|
||||
"RAW_BYTES_TARGET_REQUIRED", "raw bytes codec decodes only to byte[]");
|
||||
}
|
||||
if (encoded.length > maxBytes) {
|
||||
throw new MessageTooLargeException(
|
||||
"RAW_BYTES_TOO_LARGE", "encoded payload exceeds " + maxBytes + " bytes");
|
||||
}
|
||||
return payloadType.cast(encoded.clone());
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
/**
|
||||
* The compatibility mode a message type's schema evolution must satisfy.
|
||||
*
|
||||
* <p>Transitive modes check every historical version, not just the immediate predecessor. That
|
||||
* matters for integration events, where a consumer may be several releases behind and a chain of
|
||||
* individually-compatible changes can still be collectively breaking.
|
||||
*/
|
||||
public enum SchemaCompatibility {
|
||||
|
||||
/** A new schema can read data written by the previous schema. */
|
||||
BACKWARD,
|
||||
|
||||
/** A new schema can read data written by every previous schema. */
|
||||
BACKWARD_TRANSITIVE,
|
||||
|
||||
/** The previous schema can read data written by the new schema. */
|
||||
FORWARD,
|
||||
|
||||
/** Every previous schema can read data written by the new schema. */
|
||||
FORWARD_TRANSITIVE,
|
||||
|
||||
/** Both directions hold against the previous schema. */
|
||||
FULL,
|
||||
|
||||
/** Both directions hold against every previous schema. */
|
||||
FULL_TRANSITIVE,
|
||||
|
||||
/** No compatibility is enforced; permitted only for M2 raw bytes. */
|
||||
NONE_EXPERIMENTAL
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.error.MessageSchemaIncompatibleException;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The format-independent half of schema evolution: which versions have to be compared, and whether
|
||||
* a mode is even allowed on a production destination.
|
||||
*
|
||||
* <p>Split from the per-format gates on purpose. Whether v3 must be checked against v1 as well as
|
||||
* v2 is a property of the compatibility mode, not of Avro or Protobuf, and duplicating that
|
||||
* reasoning in each codec is how the two formats drift apart.
|
||||
*
|
||||
* <p>{@link SchemaCompatibility#NONE_EXPERIMENTAL} is refused for production destinations. A mode
|
||||
* that checks nothing is useful while a message type is being designed and actively dangerous once
|
||||
* a retained log exists, because the log outlives every consumer that could still read it.
|
||||
*/
|
||||
public final class SchemaCompatibilityValidator {
|
||||
|
||||
private final SchemaRegistry registry;
|
||||
|
||||
/**
|
||||
* Creates a validator over a registry.
|
||||
*
|
||||
* @param registry the schema source
|
||||
*/
|
||||
public SchemaCompatibilityValidator(SchemaRegistry registry) {
|
||||
this.registry = Objects.requireNonNull(registry, "registry must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the versions a candidate must be checked against, newest first.
|
||||
*
|
||||
* <p>Transitive modes return the whole history; pairwise modes return only the immediate
|
||||
* predecessor; {@link SchemaCompatibility#NONE_EXPERIMENTAL} returns nothing.
|
||||
*
|
||||
* @param subject the registry subject
|
||||
* @return the versions to compare against
|
||||
*/
|
||||
public List<SchemaVersion> versionsToCheck(String subject) {
|
||||
Objects.requireNonNull(subject, "subject must not be null");
|
||||
SchemaCompatibility mode = registry.compatibilityOf(subject);
|
||||
if (mode == SchemaCompatibility.NONE_EXPERIMENTAL) {
|
||||
return List.of();
|
||||
}
|
||||
List<SchemaVersion> history = registry.history(subject).reversed();
|
||||
if (history.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return isTransitive(mode) ? history : List.of(history.get(0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a compatibility mode that must not reach a production destination.
|
||||
*
|
||||
* @param subject the registry subject
|
||||
* @param destination the logical destination name, used in the diagnostic
|
||||
* @throws MessageSchemaIncompatibleException when the subject is unchecked
|
||||
*/
|
||||
public void requireProductionMode(String subject, String destination) {
|
||||
Objects.requireNonNull(subject, "subject must not be null");
|
||||
Objects.requireNonNull(destination, "destination must not be null");
|
||||
if (registry.compatibilityOf(subject) == SchemaCompatibility.NONE_EXPERIMENTAL) {
|
||||
throw new MessageSchemaIncompatibleException(
|
||||
"UNCHECKED_SCHEMA_ON_PRODUCTION_DESTINATION",
|
||||
"subject %s is NONE_EXPERIMENTAL and cannot back the production destination %s"
|
||||
.formatted(subject, destination));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether readers must be able to read data written by older writers.
|
||||
*
|
||||
* @param mode the compatibility mode
|
||||
* @return true when the backward direction is enforced
|
||||
*/
|
||||
public static boolean checksBackward(SchemaCompatibility mode) {
|
||||
Objects.requireNonNull(mode, "mode must not be null");
|
||||
return mode == SchemaCompatibility.BACKWARD
|
||||
|| mode == SchemaCompatibility.BACKWARD_TRANSITIVE
|
||||
|| mode == SchemaCompatibility.FULL
|
||||
|| mode == SchemaCompatibility.FULL_TRANSITIVE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether older readers must be able to read data written by the candidate.
|
||||
*
|
||||
* @param mode the compatibility mode
|
||||
* @return true when the forward direction is enforced
|
||||
*/
|
||||
public static boolean checksForward(SchemaCompatibility mode) {
|
||||
Objects.requireNonNull(mode, "mode must not be null");
|
||||
return mode == SchemaCompatibility.FORWARD
|
||||
|| mode == SchemaCompatibility.FORWARD_TRANSITIVE
|
||||
|| mode == SchemaCompatibility.FULL
|
||||
|| mode == SchemaCompatibility.FULL_TRANSITIVE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether a mode compares against the whole history.
|
||||
*
|
||||
* @param mode the compatibility mode
|
||||
* @return true for the transitive modes
|
||||
*/
|
||||
public static boolean isTransitive(SchemaCompatibility mode) {
|
||||
Objects.requireNonNull(mode, "mode must not be null");
|
||||
return mode == SchemaCompatibility.BACKWARD_TRANSITIVE
|
||||
|| mode == SchemaCompatibility.FORWARD_TRANSITIVE
|
||||
|| mode == SchemaCompatibility.FULL_TRANSITIVE;
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import java.net.URI;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Points at the schema an encoded payload was written against.
|
||||
*
|
||||
* <p>Carried alongside the bytes rather than inferred from the message type, because a consumer
|
||||
* that guesses the schema from the type is exactly the consumer that breaks when a producer rolls
|
||||
* forward.
|
||||
*
|
||||
* @param subject the registry subject or schema name
|
||||
* @param version the schema revision
|
||||
* @param schemaUri the resolvable schema location, when one exists
|
||||
*/
|
||||
public record SchemaReference(String subject, SchemaVersion version, Optional<URI> schemaUri) {
|
||||
|
||||
public SchemaReference {
|
||||
Objects.requireNonNull(version, "schema version must not be null");
|
||||
Objects.requireNonNull(schemaUri, "schemaUri must not be null");
|
||||
if (subject == null || subject.isBlank()) {
|
||||
throw new IllegalArgumentException("schema subject must not be blank");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a reference with no resolvable location.
|
||||
*
|
||||
* @param subject the registry subject
|
||||
* @param version the schema revision
|
||||
* @return a schema reference
|
||||
*/
|
||||
public static SchemaReference of(String subject, SchemaVersion version) {
|
||||
return new SchemaReference(subject, version, Optional.empty());
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Resolves schemas by subject and version, and records the compatibility mode each subject is held
|
||||
* to.
|
||||
*
|
||||
* <p>Deliberately a port. A hosted registry, a classpath directory of schema files, and a static
|
||||
* in-process map are all legitimate sources depending on the deployment, and the platform's
|
||||
* compatibility rules must hold identically across all three. Binding to a vendor client here would
|
||||
* make the rules untestable without that vendor running.
|
||||
*
|
||||
* <p>{@link #history} returns oldest first. Transitive compatibility checks read the whole list, so
|
||||
* an ordering mistake here silently converts a transitive check into a pairwise one.
|
||||
*/
|
||||
public interface SchemaRegistry {
|
||||
|
||||
/**
|
||||
* Resolves one schema definition.
|
||||
*
|
||||
* @param subject the registry subject
|
||||
* @param version the schema revision
|
||||
* @return the schema text, or empty when the subject or version is unknown
|
||||
*/
|
||||
Optional<String> lookup(String subject, SchemaVersion version);
|
||||
|
||||
/**
|
||||
* Returns every registered version of a subject, oldest first.
|
||||
*
|
||||
* @param subject the registry subject
|
||||
* @return the version history, empty when the subject is unknown
|
||||
*/
|
||||
List<SchemaVersion> history(String subject);
|
||||
|
||||
/**
|
||||
* Returns the compatibility mode enforced for a subject.
|
||||
*
|
||||
* @param subject the registry subject
|
||||
* @return the subject's compatibility mode
|
||||
*/
|
||||
SchemaCompatibility compatibilityOf(String subject);
|
||||
|
||||
/**
|
||||
* Returns the newest registered version of a subject.
|
||||
*
|
||||
* @param subject the registry subject
|
||||
* @return the latest version, or empty when the subject is unknown
|
||||
*/
|
||||
default Optional<SchemaVersion> latest(String subject) {
|
||||
List<SchemaVersion> versions = history(subject);
|
||||
return versions.isEmpty() ? Optional.empty() : Optional.of(versions.get(versions.size() - 1));
|
||||
}
|
||||
}
|
||||
+60
@@ -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);
|
||||
}
|
||||
}
|
||||
+141
@@ -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);
|
||||
}
|
||||
}
|
||||
+13
@@ -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");
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
package dev.caskeleton.messaging.api;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.messaging.api.header.HeaderName;
|
||||
import dev.caskeleton.messaging.api.header.HeaderValue;
|
||||
import dev.caskeleton.messaging.api.header.MessageHeaders;
|
||||
import dev.caskeleton.messaging.api.header.ReservedHeaders;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
/**
|
||||
* The rest of the wire boundary: values, correlation, trace propagation and the two denylists.
|
||||
*
|
||||
* <p>{@link WireSafeValueObjectTest} covers the name side. This covers what was still unbounded
|
||||
* after it: a header <em>value</em> carrying CRLF straight to the broker, a correlation id bounded
|
||||
* in Java characters rather than bytes, a {@code traceparent} that was any string at all, and two
|
||||
* denylists that matched exact spellings only.
|
||||
*/
|
||||
class WireBoundaryRejectionTest {
|
||||
|
||||
/** The C0 and DEL code points a broker disagrees with itself about. */
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {0x00, 0x09, 0x0A, 0x0D, 0x1B, 0x7F})
|
||||
@DisplayName("a header value carrying a control character is refused")
|
||||
void aHeaderValueWithAControlCharacterIsRefused(int codePoint) {
|
||||
// NUL truncates the value inside a broker that hands it to C string handling; LF and CR end
|
||||
// the header on a line-oriented binding and start one the caller wrote; ESC and DEL are
|
||||
// stripped by some intermediaries and preserved by others. Tab is refused with them because a
|
||||
// line-folding binding and a length-prefixed one disagree about whether it ends the value.
|
||||
String value = "order-" + (char) codePoint + "-created";
|
||||
|
||||
assertThatThrownBy(() -> new HeaderValue(value))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("control characters");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an ordinary header value, including non-ASCII text, is still accepted")
|
||||
void anOrdinaryHeaderValueIsAccepted() {
|
||||
assertThatCode(() -> new HeaderValue("주문 생성됨 / order created")).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a header value is bounded in bytes, not in characters")
|
||||
void aHeaderValueIsBoundedInBytes() {
|
||||
// 4096 characters of three bytes each: inside any character bound, three times the byte one.
|
||||
assertThatThrownBy(() -> new HeaderValue("가".repeat(4096)))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("UTF-8 bytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a correlation id is bounded in bytes and refuses control characters")
|
||||
void aCorrelationIdIsBoundedInBytes() {
|
||||
assertThatThrownBy(() -> new CorrelationId("가".repeat(160)))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("UTF-8 bytes");
|
||||
assertThatThrownBy(() -> new CorrelationId("flow-1\r\nmsg.id: forged"))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("control characters");
|
||||
assertThatCode(() -> new CorrelationId("flow-0198e2b1")).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(
|
||||
strings = {
|
||||
"not-a-traceparent",
|
||||
"00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331",
|
||||
"00-0AF7651916CD43DD8448EB211C80319C-b7ad6b7169203331-01",
|
||||
"ff-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
|
||||
"00-00000000000000000000000000000000-b7ad6b7169203331-01",
|
||||
"00-0af7651916cd43dd8448eb211c80319c-0000000000000000-01",
|
||||
"00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01\r\nx: y"
|
||||
})
|
||||
@DisplayName("an invalid traceparent is refused rather than propagated")
|
||||
void anInvalidTraceparentIsRefused(String traceparent) {
|
||||
// In order: not the grammar at all; no flags field; uppercase hex, which a collector comparing
|
||||
// trace ids as strings reads as a different trace; the reserved ff version; an all-zero trace
|
||||
// id and an all-zero parent span id, both of which the standard declares invalid; and a value
|
||||
// with a CRLF, which is a header injection once it is written to the traceparent header.
|
||||
assertThatThrownBy(() -> TraceContext.of(traceparent))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the W3C example traceparent is accepted")
|
||||
void theStandardExampleIsAccepted() {
|
||||
assertThatCode(() -> TraceContext.of("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("tracestate is bounded by the standard's member count and size")
|
||||
void tracestateIsBounded() {
|
||||
String parent = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01";
|
||||
|
||||
assertThatCode(
|
||||
() ->
|
||||
new TraceContext(
|
||||
Optional.of(parent),
|
||||
Optional.of("congo=t61rcWkgMzE,rojo=00f067aa0ba902b7"),
|
||||
Optional.empty()))
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
String tooManyMembers =
|
||||
java.util.stream.IntStream.range(0, 33)
|
||||
.mapToObj(index -> "k" + index + "=v")
|
||||
.collect(java.util.stream.Collectors.joining(","));
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new TraceContext(
|
||||
Optional.of(parent), Optional.of(tooManyMembers), Optional.empty()))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("32 list members");
|
||||
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new TraceContext(
|
||||
Optional.of(parent), Optional.of("congo=a\r\nx=y"), Optional.empty()))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("tracestate without a traceparent is vendor state belonging to no trace")
|
||||
void tracestateWithoutATraceparentIsRefused() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new TraceContext(
|
||||
Optional.empty(), Optional.of("congo=t61rcWkgMzE"), Optional.empty()))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("without a traceparent");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("baggage is bounded in total bytes and in member count")
|
||||
void baggageIsBounded() {
|
||||
assertThatCode(
|
||||
() ->
|
||||
new TraceContext(
|
||||
Optional.empty(), Optional.empty(), Optional.of("tenant=acme,region=eu")))
|
||||
.doesNotThrowAnyException();
|
||||
|
||||
String oversize = "k=" + "v".repeat(8200);
|
||||
assertThatThrownBy(
|
||||
() -> new TraceContext(Optional.empty(), Optional.empty(), Optional.of(oversize)))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("8192 bytes");
|
||||
|
||||
String tooManyMembers =
|
||||
java.util.stream.IntStream.range(0, 65)
|
||||
.mapToObj(index -> "k" + index + "=v")
|
||||
.collect(java.util.stream.Collectors.joining(","));
|
||||
assertThatThrownBy(
|
||||
() -> new TraceContext(Optional.empty(), Optional.empty(), Optional.of(tooManyMembers)))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("64 members");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"x-api-key", "auth-token", "db_password", "request.signature", "Cookie"})
|
||||
@DisplayName("a credential-shaped header name is refused however it is spelled")
|
||||
void aCredentialShapedNameIsRefused(String name) {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
MessageHeaders.application(Map.of(new HeaderName(name), new HeaderValue("opaque"))))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("not allowed");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a name that merely contains the letters of a secret is still accepted")
|
||||
void aNameThatMerelyContainsTheLettersIsAccepted() {
|
||||
assertThatCode(
|
||||
() ->
|
||||
MessageHeaders.application(
|
||||
Map.of(
|
||||
new HeaderName("tokenizer-version"), new HeaderValue("3"),
|
||||
new HeaderName("secretariat-id"), new HeaderValue("s-9"))))
|
||||
.as("segment matching, not substring matching")
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the platform namespace is reserved whether or not the name exists yet")
|
||||
void thePlatformNamespaceIsReserved() {
|
||||
assertThat(ReservedHeaders.isReserved("msg.not-defined-in-this-release")).isTrue();
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
MessageHeaders.application(
|
||||
Map.of(new HeaderName("msg.not-defined-yet"), new HeaderValue("mine"))))
|
||||
.isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("not allowed");
|
||||
|
||||
// The platform factory still writes its own namespace; that is the whole distinction.
|
||||
assertThatCode(
|
||||
() ->
|
||||
MessageHeaders.platform(
|
||||
Map.of(new HeaderName(ReservedHeaders.MESSAGE_ID), new HeaderValue("m-1"))))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
+129
@@ -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"));
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
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.supported()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@org.junit.jupiter.api.DisplayName("이름 붙인 capability만 지원하고 넘긴 집합을 나중에 바꿔도 영향이 없다")
|
||||
void aCapabilitySetSupportsExactlyWhatWasNamedAndIgnoresLaterChangesToTheInput() {
|
||||
// given
|
||||
java.util.Set<MessagingCapabilities.Capability> input =
|
||||
java.util.EnumSet.of(MessagingCapabilities.Capability.ORDERED_STREAM);
|
||||
MessagingCapabilities capabilities = new MessagingCapabilities(input);
|
||||
|
||||
// when
|
||||
input.add(MessagingCapabilities.Capability.DEDUPLICATED_PUBLISH);
|
||||
|
||||
// then
|
||||
assertThat(capabilities.supports(MessagingCapabilities.Capability.ORDERED_STREAM)).isTrue();
|
||||
assertThat(capabilities.supports(MessagingCapabilities.Capability.DEDUPLICATED_PUBLISH))
|
||||
.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);
|
||||
}
|
||||
}
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
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.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PublishResultTest {
|
||||
|
||||
/** A coordinate no adapter would have produced for a message that never left. */
|
||||
private static final BrokerPosition POSITION =
|
||||
new BrokerPosition() {
|
||||
@Override
|
||||
public String broker() {
|
||||
return "kafka";
|
||||
}
|
||||
|
||||
@Override
|
||||
public java.util.Map<String, String> diagnosticAttributes() {
|
||||
return java.util.Map.of("topic", "order-events", "partition", "0", "offset", "17");
|
||||
}
|
||||
};
|
||||
|
||||
private static final FailureDescriptor AMBIGUOUS_FAILURE =
|
||||
FailureDescriptor.of(FailureCategory.AMBIGUOUS, "CONFIRM_TIMEOUT", "confirm timed out");
|
||||
|
||||
@Test
|
||||
void aRejectionCannotClaimTheBrokerAcceptedIt() {
|
||||
PublishEvidence accepted =
|
||||
PublishEvidence.confirmed(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK);
|
||||
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new PublishResult(
|
||||
PublishCompletion.REJECTED,
|
||||
accepted,
|
||||
RoutingOutcome.ROUTED,
|
||||
Optional.empty(),
|
||||
1,
|
||||
Duration.ofMillis(10),
|
||||
Optional.of(AMBIGUOUS_FAILURE)))
|
||||
.as("re-publishing a message the broker acknowledged is how one order becomes two")
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConfirmationCannotBeUnsureWhetherItRouted() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new PublishResult(
|
||||
PublishCompletion.CONFIRMED,
|
||||
PublishEvidence.confirmed(ConfirmationLevel.BROKER_ACK),
|
||||
RoutingOutcome.UNKNOWN,
|
||||
Optional.empty(),
|
||||
1,
|
||||
Duration.ofMillis(10),
|
||||
Optional.empty()))
|
||||
.as("the response that confirmed the publish is the one that says whether it routed")
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoutedPublishIsNotAmbiguous() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new PublishResult(
|
||||
PublishCompletion.AMBIGUOUS,
|
||||
PublishEvidence.ambiguous(),
|
||||
RoutingOutcome.ROUTED,
|
||||
Optional.empty(),
|
||||
1,
|
||||
Duration.ofMillis(10),
|
||||
Optional.of(AMBIGUOUS_FAILURE)))
|
||||
.as("only the broker can report routing, and a broker that reported it answered")
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUntransmittedPublishHasNoBrokerPosition() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new PublishResult(
|
||||
PublishCompletion.REJECTED,
|
||||
PublishEvidence.notTransmitted(),
|
||||
RoutingOutcome.NOT_APPLICABLE,
|
||||
Optional.of(POSITION),
|
||||
1,
|
||||
Duration.ofMillis(10),
|
||||
Optional.of(AMBIGUOUS_FAILURE)))
|
||||
.as("a coordinate for bytes that never left belongs to some other message")
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@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
|
||||
@DisplayName("거부 factory는 전송되지 않았고 라우팅 대상이 아닌 결과를 만든다")
|
||||
void theRejectedFactoryReportsNothingWasTransmittedOrRouted() {
|
||||
// when
|
||||
PublishResult result = PublishResult.rejected(Duration.ofMillis(3), AMBIGUOUS_FAILURE);
|
||||
|
||||
// then
|
||||
assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED);
|
||||
assertThat(result.evidence()).isEqualTo(PublishEvidence.notTransmitted());
|
||||
assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.NOT_APPLICABLE);
|
||||
assertThat(result.failure()).contains(AMBIGUOUS_FAILURE);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("모호 factory는 브로커가 메시지를 가졌을 수 있다고 보고한다")
|
||||
void theAmbiguousFactoryReportsTheBrokerMayHoldTheMessage() {
|
||||
// when
|
||||
PublishResult result = PublishResult.ambiguous(Duration.ofMillis(3), AMBIGUOUS_FAILURE);
|
||||
|
||||
// then
|
||||
assertThat(result.mayHaveBeenStored()).isTrue();
|
||||
assertThat(result.evidence()).isEqualTo(PublishEvidence.ambiguous());
|
||||
assertThat(result.routingOutcome()).isEqualTo(RoutingOutcome.UNKNOWN);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("확인 factory는 브로커 수락과 위치를 담고 실패 설명은 없다")
|
||||
void theConfirmedFactoryCarriesAcceptanceAndPositionWithoutAFailure() {
|
||||
// when
|
||||
PublishResult result =
|
||||
PublishResult.confirmed(
|
||||
ConfirmationLevel.BROKER_ACK,
|
||||
RoutingOutcome.NOT_APPLICABLE,
|
||||
Optional.of(POSITION),
|
||||
Duration.ofMillis(3));
|
||||
|
||||
// then
|
||||
assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED);
|
||||
assertThat(result.evidence().brokerAccepted()).isTrue();
|
||||
assertThat(result.position()).contains(POSITION);
|
||||
assertThat(result.failure()).isEmpty();
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.messaging.api.error.MessageTooLargeException;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The boundary the codecs delegate to.
|
||||
*
|
||||
* <p>Each codec used to serialize into an unbounded buffer and compare the finished length to the
|
||||
* limit. That check reports an oversized payload; it does not prevent one. The difference only
|
||||
* shows up for a payload whose serialized form is orders of magnitude larger than the bound, which
|
||||
* is precisely the case that matters — the consumer is out of heap before the comparison runs.
|
||||
*/
|
||||
class BoundedByteSinkTest {
|
||||
|
||||
private static final int MAX = 64;
|
||||
|
||||
@Test
|
||||
@DisplayName("one byte under, exactly at, and one byte over the limit")
|
||||
void theLimitIsInclusiveAndTheNextByteIsRefused() {
|
||||
assertThatCode(() -> fill(MAX - 1)).doesNotThrowAnyException();
|
||||
assertThatCode(() -> fill(MAX)).doesNotThrowAnyException();
|
||||
|
||||
assertThatThrownBy(() -> fill(MAX + 1))
|
||||
.isInstanceOf(MessageTooLargeException.class)
|
||||
.hasMessageContaining("refused at byte 65");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a much larger stream stops at the limit rather than after allocation")
|
||||
void aMuchLargerStreamStopsAtTheLimit() {
|
||||
BoundedByteSink sink = BoundedByteSink.of(MAX, "PAYLOAD_TOO_LARGE");
|
||||
|
||||
assertThatThrownBy(
|
||||
() -> {
|
||||
// Ten mebibytes offered one kibibyte at a time. A buffer-then-check codec would have
|
||||
// held all of it; this refuses the chunk that crosses the bound.
|
||||
for (int chunk = 0; chunk < 10_240; chunk++) {
|
||||
sink.write(new byte[1_024], 0, 1_024);
|
||||
}
|
||||
})
|
||||
.isInstanceOf(MessageTooLargeException.class);
|
||||
|
||||
assertThat(sink.written())
|
||||
.as("nothing beyond the bound was ever admitted")
|
||||
.isLessThanOrEqualTo(MAX);
|
||||
assertThat(sink.toByteArray()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a pre-flight size check does not consume the budget")
|
||||
void aPreFlightCheckDoesNotConsumeTheBudget() {
|
||||
BoundedByteSink sink = BoundedByteSink.of(MAX, "PAYLOAD_TOO_LARGE");
|
||||
|
||||
sink.requireFits(MAX);
|
||||
|
||||
assertThat(sink.written()).isZero();
|
||||
assertThatCode(() -> sink.write(new byte[MAX], 0, MAX)).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a pre-flight check refuses a size that cannot fit")
|
||||
void aPreFlightCheckRefusesASizeThatCannotFit() {
|
||||
BoundedByteSink sink = BoundedByteSink.of(MAX, "AVRO_PAYLOAD_TOO_LARGE");
|
||||
|
||||
assertThatThrownBy(() -> sink.requireFits(MAX + 1))
|
||||
.isInstanceOf(MessageTooLargeException.class)
|
||||
.asInstanceOf(
|
||||
org.assertj.core.api.InstanceOfAssertFactories.type(MessageTooLargeException.class))
|
||||
.extracting(failure -> failure.failure().code())
|
||||
.as("the sink reports the codec's own code, not a generic one")
|
||||
.isEqualTo("AVRO_PAYLOAD_TOO_LARGE");
|
||||
}
|
||||
|
||||
private static byte[] fill(int size) {
|
||||
BoundedByteSink sink = BoundedByteSink.of(MAX, "PAYLOAD_TOO_LARGE");
|
||||
for (int index = 0; index < size; index++) {
|
||||
sink.write('a');
|
||||
}
|
||||
return sink.toByteArray();
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.error.MessageSerializationException;
|
||||
import dev.caskeleton.messaging.api.error.MessageTooLargeException;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RawBytesMessageCodecTest {
|
||||
|
||||
private static final MessageType OPAQUE = new MessageType("opaque.blob");
|
||||
private static final SchemaVersion V1 = new SchemaVersion(1);
|
||||
|
||||
private final RawBytesMessageCodec codec = new RawBytesMessageCodec();
|
||||
|
||||
@Test
|
||||
void roundTripsOpaqueBytes() {
|
||||
byte[] payload = {1, 2, 3, 4};
|
||||
|
||||
EncodedMessage encoded = codec.encode(OPAQUE, V1, payload);
|
||||
|
||||
assertThat(codec.decode(OPAQUE, V1, encoded.bytes(), byte[].class)).containsExactly(1, 2, 3, 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void advertisesOpaqueContentTypeAndNoSchemaReference() {
|
||||
EncodedMessage encoded = codec.encode(OPAQUE, V1, new byte[] {9});
|
||||
|
||||
assertThat(codec.contentType()).isEqualTo(ContentType.OCTET_STREAM);
|
||||
assertThat(encoded.schemaReference()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesNonByteArrayPayloads() {
|
||||
assertThatThrownBy(() -> codec.encode(OPAQUE, V1, "text"))
|
||||
.isInstanceOf(MessageSerializationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesDecodingToAnythingButByteArray() {
|
||||
assertThatThrownBy(() -> codec.decode(OPAQUE, V1, new byte[] {1}, String.class))
|
||||
.isInstanceOf(MessageSerializationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void enforcesTheByteLimit() {
|
||||
RawBytesMessageCodec small = new RawBytesMessageCodec(4);
|
||||
|
||||
assertThatThrownBy(() -> small.encode(OPAQUE, V1, new byte[5]))
|
||||
.isInstanceOf(MessageTooLargeException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodedMessageDefensivelyCopiesItsBytes() {
|
||||
byte[] source = {1, 2, 3};
|
||||
EncodedMessage encoded = new EncodedMessage(source, ContentType.OCTET_STREAM, Optional.empty());
|
||||
|
||||
source[0] = 99;
|
||||
|
||||
assertThat(encoded.bytes()).containsExactly(1, 2, 3);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package dev.caskeleton.messaging.schema;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.error.MessageSchemaIncompatibleException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SchemaCompatibilityValidatorTest {
|
||||
|
||||
private static final SchemaVersion V1 = new SchemaVersion(1);
|
||||
private static final SchemaVersion V2 = new SchemaVersion(2);
|
||||
private static final SchemaVersion V3 = new SchemaVersion(3);
|
||||
|
||||
/** A registry whose history is deliberately oldest-first, as the port documents. */
|
||||
private record FixedRegistry(List<SchemaVersion> versions, SchemaCompatibility mode)
|
||||
implements SchemaRegistry {
|
||||
|
||||
@Override
|
||||
public Optional<String> lookup(String subject, SchemaVersion version) {
|
||||
return versions.contains(version) ? Optional.of("{}") : Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SchemaVersion> history(String subject) {
|
||||
return versions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SchemaCompatibility compatibilityOf(String subject) {
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
|
||||
private static SchemaCompatibilityValidator validator(SchemaCompatibility mode) {
|
||||
return new SchemaCompatibilityValidator(new FixedRegistry(List.of(V1, V2, V3), mode));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPairwiseModeChecksOnlyTheImmediatePredecessor() {
|
||||
assertThat(validator(SchemaCompatibility.BACKWARD).versionsToCheck("order.created"))
|
||||
.containsExactly(V3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTransitiveModeChecksTheWholeHistoryNewestFirst() {
|
||||
assertThat(validator(SchemaCompatibility.BACKWARD_TRANSITIVE).versionsToCheck("order.created"))
|
||||
.as(
|
||||
"a chain of individually compatible changes can still break a consumer several releases behind")
|
||||
.containsExactly(V3, V2, V1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUncheckedModeComparesAgainstNothing() {
|
||||
assertThat(validator(SchemaCompatibility.NONE_EXPERIMENTAL).versionsToCheck("order.created"))
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEmptyHistoryHasNothingToCompareAgainst() {
|
||||
SchemaCompatibilityValidator validator =
|
||||
new SchemaCompatibilityValidator(
|
||||
new FixedRegistry(List.of(), SchemaCompatibility.FULL_TRANSITIVE));
|
||||
|
||||
assertThat(validator.versionsToCheck("order.created")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUncheckedSubjectCannotBackAProductionDestination() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
validator(SchemaCompatibility.NONE_EXPERIMENTAL)
|
||||
.requireProductionMode("order.created", "orders.v1"))
|
||||
.isInstanceOf(MessageSchemaIncompatibleException.class)
|
||||
.hasMessageContaining("orders.v1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCheckedSubjectMayBackAProductionDestination() {
|
||||
assertThatCode(
|
||||
() ->
|
||||
validator(SchemaCompatibility.FULL)
|
||||
.requireProductionMode("order.created", "orders.v1"))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullModeEnforcesBothDirections() {
|
||||
assertThat(SchemaCompatibilityValidator.checksBackward(SchemaCompatibility.FULL)).isTrue();
|
||||
assertThat(SchemaCompatibilityValidator.checksForward(SchemaCompatibility.FULL)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachOneDirectionalModeEnforcesOnlyItsOwnDirection() {
|
||||
assertThat(SchemaCompatibilityValidator.checksForward(SchemaCompatibility.BACKWARD)).isFalse();
|
||||
assertThat(SchemaCompatibilityValidator.checksBackward(SchemaCompatibility.FORWARD)).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLatestVersionIsTheNewestNotTheFirstListed() {
|
||||
SchemaRegistry registry = new FixedRegistry(List.of(V1, V2, V3), SchemaCompatibility.FULL);
|
||||
|
||||
assertThat(registry.latest("order.created")).hasValue(V3);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user