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

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

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

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

미완: 계획서가 요구한 실 브로커 IT 40개 중 7개만 작성.
Rabbit 13 / Outbox 6 / Inbox 4 / NATS·Pulsar·Share 5 / testkit 2 /
starter·admin 3, 그리고 TLS·ACL 2개가 남음.
This commit is contained in:
DongHyeonka
2026-08-14 14:55:38 +09:00
parent 432130fd62
commit e23ed9486e
475 changed files with 39748 additions and 0 deletions
@@ -0,0 +1,5 @@
apply plugin: 'java-library'
dependencies {
api project(':messaging:messaging-core-api')
}
@@ -0,0 +1,83 @@
# 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.3=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.0=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.2=spotbugs
org.apache.logging.log4j:log4j-core:2.25.2=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.6=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.0=annotationProcessor,checkstyle,testAnnotationProcessor,testCompileClasspath
org.junit.jupiter:junit-jupiter-api:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.1=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.1=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.1=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.1=testRuntimeClasspath
org.junit:junit-bom:6.0.1=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.17=spotbugs,spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.17=checkstyle,spotbugsSlf4j
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
empty=compileClasspath,runtimeClasspath
@@ -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 + "]";
}
}
@@ -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);
}
}
@@ -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();
}
@@ -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());
}
}
@@ -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
}
@@ -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;
}
}
@@ -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());
}
}
@@ -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));
}
}
@@ -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);
}
}
@@ -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);
}
}