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:
+126
@@ -0,0 +1,126 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.ProducerId;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.TraceContext;
|
||||
import dev.caskeleton.messaging.api.UuidV7;
|
||||
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 java.util.concurrent.TimeUnit;
|
||||
import org.openjdk.jmh.annotations.Benchmark;
|
||||
import org.openjdk.jmh.annotations.BenchmarkMode;
|
||||
import org.openjdk.jmh.annotations.Fork;
|
||||
import org.openjdk.jmh.annotations.Measurement;
|
||||
import org.openjdk.jmh.annotations.Mode;
|
||||
import org.openjdk.jmh.annotations.OutputTimeUnit;
|
||||
import org.openjdk.jmh.annotations.Scope;
|
||||
import org.openjdk.jmh.annotations.Setup;
|
||||
import org.openjdk.jmh.annotations.State;
|
||||
import org.openjdk.jmh.annotations.Warmup;
|
||||
import org.openjdk.jmh.infra.Blackhole;
|
||||
|
||||
/**
|
||||
* Measures the per-message cost the platform adds before any broker is involved.
|
||||
*
|
||||
* <p>This is the number the platform is accountable for. Broker latency dominates any real publish
|
||||
* and varies with the network, so measuring it would tell you about the test environment; envelope
|
||||
* construction, header validation, and id generation happen on the calling thread on every message
|
||||
* and are entirely the platform's.
|
||||
*
|
||||
* <p>Header validation is benchmarked separately from envelope construction because they scale
|
||||
* differently: construction is constant, while validation is linear in the header count and is the
|
||||
* part that a caller can make expensive by accident.
|
||||
*/
|
||||
@BenchmarkMode(Mode.AverageTime)
|
||||
@OutputTimeUnit(TimeUnit.NANOSECONDS)
|
||||
@Warmup(iterations = 3, time = 1)
|
||||
@Measurement(iterations = 5, time = 1)
|
||||
@Fork(1)
|
||||
@State(Scope.Benchmark)
|
||||
public class EnvelopeCodecBenchmark {
|
||||
|
||||
private Map<HeaderName, HeaderValue> fewHeaders;
|
||||
private Map<HeaderName, HeaderValue> manyHeaders;
|
||||
private Instant now;
|
||||
|
||||
/** Builds the header maps once, so the benchmark measures validation and not map construction. */
|
||||
@Setup
|
||||
public void setUp() {
|
||||
now = Instant.parse("2026-08-10T09:15:00Z");
|
||||
fewHeaders = headers(3);
|
||||
manyHeaders = headers(32);
|
||||
}
|
||||
|
||||
private static Map<HeaderName, HeaderValue> headers(int count) {
|
||||
Map<HeaderName, HeaderValue> headers = new LinkedHashMap<>();
|
||||
for (int index = 0; index < count; index++) {
|
||||
headers.put(new HeaderName("x-app-" + index), new HeaderValue("value-" + index));
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures monotonic id generation, which every published message pays for.
|
||||
*
|
||||
* @param blackhole consumes the result
|
||||
*/
|
||||
@Benchmark
|
||||
public void generateMessageId(Blackhole blackhole) {
|
||||
blackhole.consume(UuidV7.next());
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures header validation with a typical header count.
|
||||
*
|
||||
* @param blackhole consumes the result
|
||||
*/
|
||||
@Benchmark
|
||||
public void validateFewHeaders(Blackhole blackhole) {
|
||||
blackhole.consume(MessageHeaders.application(fewHeaders));
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures header validation near the count limit, where the cost is linear.
|
||||
*
|
||||
* @param blackhole consumes the result
|
||||
*/
|
||||
@Benchmark
|
||||
public void validateManyHeaders(Blackhole blackhole) {
|
||||
blackhole.consume(MessageHeaders.application(manyHeaders));
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures building one complete envelope.
|
||||
*
|
||||
* @param blackhole consumes the result
|
||||
*/
|
||||
@Benchmark
|
||||
public void buildEnvelope(Blackhole blackhole) {
|
||||
blackhole.consume(
|
||||
new MessageEnvelope<>(
|
||||
MessageId.newId(),
|
||||
new MessageType("order.created"),
|
||||
new SchemaVersion(1),
|
||||
now,
|
||||
Optional.of(now),
|
||||
new ProducerId("order-api"),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
ContentType.JSON,
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
TraceContext.none(),
|
||||
MessageHeaders.application(fewHeaders),
|
||||
"{\"orderId\":\"o-1\"}"));
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Which failure scenarios each adapter has actually been run against.
|
||||
*
|
||||
* <p>Records coverage, not capability. An adapter that has never been run under {@code
|
||||
* connection-cut-after-write} may well handle it correctly — the point is that nobody knows, and a
|
||||
* support matrix that does not distinguish "verified" from "probably fine" is how an unproven
|
||||
* adapter ends up in production.
|
||||
*
|
||||
* <p>A Stable adapter must cover every scenario. That rule is enforced by a test rather than
|
||||
* documented, because a promotion to Stable is exactly the moment the gap would otherwise be
|
||||
* overlooked.
|
||||
*/
|
||||
public final class BrokerFailureMatrix {
|
||||
|
||||
private final Map<String, Map<String, Coverage>> coverage = new LinkedHashMap<>();
|
||||
|
||||
/** How a scenario is covered for one adapter. */
|
||||
public enum Coverage {
|
||||
/** Run against a deterministic harness. */
|
||||
DETERMINISTIC,
|
||||
/** Run against a live broker in a container. */
|
||||
LIVE_BROKER,
|
||||
/** Not run. */
|
||||
NOT_COVERED
|
||||
}
|
||||
|
||||
/**
|
||||
* Records how one adapter covers one scenario.
|
||||
*
|
||||
* @param adapter the adapter module name
|
||||
* @param scenario the scenario
|
||||
* @param level how it is covered
|
||||
* @return this matrix
|
||||
*/
|
||||
public BrokerFailureMatrix record(String adapter, NetworkFaultScenario scenario, Coverage level) {
|
||||
Objects.requireNonNull(scenario, "scenario must not be null");
|
||||
Objects.requireNonNull(level, "level must not be null");
|
||||
if (adapter == null || adapter.isBlank()) {
|
||||
throw new IllegalArgumentException("adapter must not be blank");
|
||||
}
|
||||
coverage.computeIfAbsent(adapter, key -> new LinkedHashMap<>()).put(scenario.name(), level);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns how an adapter covers a scenario.
|
||||
*
|
||||
* @param adapter the adapter module name
|
||||
* @param scenario the scenario
|
||||
* @return the coverage level, {@link Coverage#NOT_COVERED} when nothing was recorded
|
||||
*/
|
||||
public Coverage coverageOf(String adapter, NetworkFaultScenario scenario) {
|
||||
return Optional.ofNullable(coverage.get(adapter))
|
||||
.map(scenarios -> scenarios.get(scenario.name()))
|
||||
.orElse(Coverage.NOT_COVERED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the scenarios an adapter has never been run against.
|
||||
*
|
||||
* @param adapter the adapter module name
|
||||
* @return the uncovered scenarios
|
||||
*/
|
||||
public List<NetworkFaultScenario> gapsFor(String adapter) {
|
||||
return NetworkFaultScenario.all().stream()
|
||||
.filter(scenario -> coverageOf(adapter, scenario) == Coverage.NOT_COVERED)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether an adapter covers every scenario.
|
||||
*
|
||||
* @param adapter the adapter module name
|
||||
* @return true when nothing is uncovered
|
||||
*/
|
||||
public boolean isComplete(String adapter) {
|
||||
return gapsFor(adapter).isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the adapters this matrix has any record for.
|
||||
*
|
||||
* @return the recorded adapter names
|
||||
*/
|
||||
public List<String> adapters() {
|
||||
return List.copyOf(coverage.keySet());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the matrix the platform ships with.
|
||||
*
|
||||
* <p>Kafka and RabbitMQ are Stable and cover everything. The experimental adapters cover the
|
||||
* deterministic scenarios their contract suite exercises and are explicitly recorded as having no
|
||||
* live-broker coverage — which is what makes their Experimental tier a statement of fact rather
|
||||
* than a disclaimer.
|
||||
*
|
||||
* @return the shipped coverage matrix
|
||||
*/
|
||||
public static BrokerFailureMatrix shipped() {
|
||||
BrokerFailureMatrix matrix = new BrokerFailureMatrix();
|
||||
for (NetworkFaultScenario scenario : NetworkFaultScenario.all()) {
|
||||
matrix.record("messaging-kafka", scenario, Coverage.LIVE_BROKER);
|
||||
matrix.record("messaging-rabbit", scenario, Coverage.LIVE_BROKER);
|
||||
}
|
||||
matrix.record(
|
||||
"messaging-pulsar-experimental",
|
||||
NetworkFaultScenario.CONNECTION_CUT_AFTER_WRITE,
|
||||
Coverage.DETERMINISTIC);
|
||||
matrix.record(
|
||||
"messaging-pulsar-experimental",
|
||||
NetworkFaultScenario.CONFIRM_TIMEOUT,
|
||||
Coverage.DETERMINISTIC);
|
||||
matrix.record(
|
||||
"messaging-nats-experimental",
|
||||
NetworkFaultScenario.CONNECTION_CUT_AFTER_WRITE,
|
||||
Coverage.DETERMINISTIC);
|
||||
matrix.record(
|
||||
"messaging-nats-experimental",
|
||||
NetworkFaultScenario.CONFIRM_TIMEOUT,
|
||||
Coverage.DETERMINISTIC);
|
||||
return matrix;
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* The certified broker versions and support tier for every adapter.
|
||||
*
|
||||
* <p>Held as code with a test over it rather than as a document, because a support matrix that
|
||||
* lives only in prose drifts the first time an adapter is added. The test asserts the rules the
|
||||
* design fixes: a Stable adapter must run the shared contract, and an Experimental adapter must be
|
||||
* disabled by default.
|
||||
*/
|
||||
public final class CompatibilityMatrix {
|
||||
|
||||
private CompatibilityMatrix() {}
|
||||
|
||||
/** The support tier an adapter has earned. */
|
||||
public enum Tier {
|
||||
/** Passes the shared adapter contract unchanged. */
|
||||
STABLE,
|
||||
|
||||
/** Contract coverage is still being proven; disabled by default. */
|
||||
EXPERIMENTAL,
|
||||
|
||||
/** Adapter SPI only; outside the supported set. */
|
||||
EXTENSION
|
||||
}
|
||||
|
||||
/**
|
||||
* One certified adapter.
|
||||
*
|
||||
* @param adapter the module name
|
||||
* @param brokerVersions the broker versions the adapter is certified against
|
||||
* @param tier the support tier
|
||||
* @param runsSharedContract whether the module runs {@link MessagingAdapterContract}
|
||||
* @param enabledByDefault whether the adapter is active without an explicit opt-in
|
||||
* @param hasLiveBrokerCertification whether a container-backed suite exercises a real broker
|
||||
*/
|
||||
public record Entry(
|
||||
String adapter,
|
||||
List<String> brokerVersions,
|
||||
Tier tier,
|
||||
boolean runsSharedContract,
|
||||
boolean enabledByDefault,
|
||||
boolean hasLiveBrokerCertification) {
|
||||
|
||||
public Entry {
|
||||
Objects.requireNonNull(tier, "tier must not be null");
|
||||
Objects.requireNonNull(brokerVersions, "brokerVersions must not be null");
|
||||
if (adapter == null || adapter.isBlank()) {
|
||||
throw new IllegalArgumentException("adapter must not be blank");
|
||||
}
|
||||
if (brokerVersions.isEmpty()) {
|
||||
throw new IllegalArgumentException("an adapter must certify at least one broker version");
|
||||
}
|
||||
brokerVersions = List.copyOf(brokerVersions);
|
||||
}
|
||||
}
|
||||
|
||||
private static final Map<String, Entry> ENTRIES =
|
||||
Map.of(
|
||||
"messaging-kafka",
|
||||
new Entry("messaging-kafka", List.of("4.2", "4.3"), Tier.STABLE, true, true, true),
|
||||
"messaging-rabbit",
|
||||
new Entry("messaging-rabbit", List.of("4.3"), Tier.STABLE, true, true, true),
|
||||
"messaging-kafka-share-experimental",
|
||||
new Entry(
|
||||
"messaging-kafka-share-experimental",
|
||||
List.of("4.2", "4.3"),
|
||||
Tier.EXPERIMENTAL,
|
||||
false,
|
||||
false,
|
||||
false),
|
||||
"messaging-pulsar-experimental",
|
||||
new Entry(
|
||||
"messaging-pulsar-experimental",
|
||||
List.of("4.0", "4.2"),
|
||||
Tier.EXPERIMENTAL,
|
||||
false,
|
||||
false,
|
||||
false),
|
||||
"messaging-nats-experimental",
|
||||
new Entry(
|
||||
"messaging-nats-experimental",
|
||||
List.of("2.14"),
|
||||
Tier.EXPERIMENTAL,
|
||||
false,
|
||||
false,
|
||||
false));
|
||||
|
||||
/**
|
||||
* Returns every certified adapter.
|
||||
*
|
||||
* @return the entries, keyed by module name
|
||||
*/
|
||||
public static Map<String, Entry> entries() {
|
||||
return ENTRIES;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns one adapter's entry.
|
||||
*
|
||||
* @param adapter the module name
|
||||
* @return the entry
|
||||
*/
|
||||
public static Entry of(String adapter) {
|
||||
Entry entry = ENTRIES.get(adapter);
|
||||
if (entry == null) {
|
||||
throw new IllegalArgumentException("adapter is not in the compatibility matrix: " + adapter);
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.messaging.api.publish.ConfirmationLevel;
|
||||
import dev.caskeleton.messaging.api.publish.PublishCompletion;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import dev.caskeleton.messaging.api.publish.TransmissionEvidence;
|
||||
|
||||
/** Assertions every adapter's contract run shares. */
|
||||
public final class ContractAssertions {
|
||||
|
||||
private ContractAssertions() {}
|
||||
|
||||
/**
|
||||
* Asserts a publish confirmed with real broker evidence.
|
||||
*
|
||||
* @param result the publish outcome
|
||||
*/
|
||||
public static void assertConfirmed(PublishResult result) {
|
||||
assertThat(result.completion()).isEqualTo(PublishCompletion.CONFIRMED);
|
||||
assertThat(result.evidence().brokerAccepted()).isTrue();
|
||||
assertThat(result.evidence().confirmationLevel()).isNotEqualTo(ConfirmationLevel.NONE);
|
||||
assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.TRANSMITTED);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts a publish reported ambiguity without claiming any confirmation.
|
||||
*
|
||||
* @param result the publish outcome
|
||||
*/
|
||||
public static void assertAmbiguous(PublishResult result) {
|
||||
assertThat(result.completion()).isEqualTo(PublishCompletion.AMBIGUOUS);
|
||||
assertThat(result.evidence().confirmationLevel()).isEqualTo(ConfirmationLevel.NONE);
|
||||
assertThat(result.evidence().brokerAccepted()).isFalse();
|
||||
assertThat(result.evidence().transmission())
|
||||
.isEqualTo(TransmissionEvidence.MAY_HAVE_BEEN_TRANSMITTED);
|
||||
assertThat(result.mayHaveBeenStored()).isTrue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts a publish was refused before anything left the process.
|
||||
*
|
||||
* @param result the publish outcome
|
||||
*/
|
||||
public static void assertRejectedLocally(PublishResult result) {
|
||||
assertThat(result.completion()).isEqualTo(PublishCompletion.REJECTED);
|
||||
assertThat(result.evidence().transmission()).isEqualTo(TransmissionEvidence.NOT_TRANSMITTED);
|
||||
assertThat(result.failure()).isPresent();
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.ProducerId;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.TraceContext;
|
||||
import dev.caskeleton.messaging.api.header.MessageHeaders;
|
||||
import dev.caskeleton.messaging.schema.EncodedMessage;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* The standard messages every adapter contract run uses.
|
||||
*
|
||||
* <p>Fixed rather than random so that a failure in one adapter can be compared byte for byte
|
||||
* against another. The oversized variant exists to prove the payload limit is enforced locally: an
|
||||
* adapter that lets it reach the broker turns a deterministic rejection into a broker-specific
|
||||
* error.
|
||||
*
|
||||
* @param envelope the encoded envelope to publish
|
||||
*/
|
||||
public record ContractMessage(MessageEnvelope<EncodedMessage> envelope) {
|
||||
|
||||
private static final Instant FIXED_TIME = Instant.parse("2026-08-10T09:15:00Z");
|
||||
|
||||
public ContractMessage {
|
||||
Objects.requireNonNull(envelope, "envelope must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the standard small event.
|
||||
*
|
||||
* @return a contract message under every limit
|
||||
*/
|
||||
public static ContractMessage orderCreated() {
|
||||
return of("{\"orderId\":\"o-1\"}".getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a message one byte above the one mebibyte portability limit.
|
||||
*
|
||||
* @return an oversized contract message
|
||||
*/
|
||||
public static ContractMessage oversized() {
|
||||
return of(new byte[1_048_577]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a contract message around explicit payload bytes.
|
||||
*
|
||||
* @param payload the encoded payload
|
||||
* @return a contract message
|
||||
*/
|
||||
public static ContractMessage of(byte[] payload) {
|
||||
return new ContractMessage(
|
||||
new MessageEnvelope<>(
|
||||
MessageId.newId(),
|
||||
new MessageType("order.created"),
|
||||
new SchemaVersion(1),
|
||||
FIXED_TIME,
|
||||
Optional.of(FIXED_TIME),
|
||||
new ProducerId("contract-suite"),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
ContentType.JSON,
|
||||
Optional.of("acct-1"),
|
||||
Optional.of("acct-1"),
|
||||
Optional.empty(),
|
||||
TraceContext.none(),
|
||||
MessageHeaders.empty(),
|
||||
new EncodedMessage(payload, ContentType.JSON, Optional.empty())));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the logical identity of this message.
|
||||
*
|
||||
* @return the message id
|
||||
*/
|
||||
public MessageId messageId() {
|
||||
return envelope.messageId();
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
/**
|
||||
* Reports whether a container runtime is reachable.
|
||||
*
|
||||
* <p>Live-broker suites are guarded on this rather than assumed. A developer machine or a build
|
||||
* agent without Docker should skip them with a stated reason, not fail with a connection error that
|
||||
* looks like a product defect — and the release gate checks separately that the suites actually ran
|
||||
* where they were supposed to.
|
||||
*/
|
||||
public final class DockerAvailability {
|
||||
|
||||
private static final boolean AVAILABLE = probe();
|
||||
|
||||
private DockerAvailability() {}
|
||||
|
||||
/**
|
||||
* Reports whether a container runtime is available.
|
||||
*
|
||||
* @return true when containers can be started
|
||||
*/
|
||||
public static boolean isAvailable() {
|
||||
return AVAILABLE;
|
||||
}
|
||||
|
||||
private static boolean probe() {
|
||||
try {
|
||||
Class<?> factory = Class.forName("org.testcontainers.DockerClientFactory");
|
||||
Object instance = factory.getMethod("instance").invoke(null);
|
||||
return (boolean) factory.getMethod("isDockerAvailable").invoke(instance);
|
||||
} catch (ReflectiveOperationException | RuntimeException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
/**
|
||||
* Injects the faults an adapter must survive.
|
||||
*
|
||||
* <p>Each fault targets an <em>acknowledgement</em>, not the operation itself. That is the point:
|
||||
* losing a confirm is what makes an outcome ambiguous, and an adapter is only trustworthy if it
|
||||
* reports the ambiguity rather than guessing which way it went.
|
||||
*/
|
||||
public interface FaultController {
|
||||
|
||||
/** Makes the next publish complete without a broker confirmation. */
|
||||
void dropPublishConfirmation();
|
||||
|
||||
/** Makes the next settlement complete without a broker confirmation. */
|
||||
void dropSettlementConfirmation();
|
||||
|
||||
/** Makes publishes to the dead letter destination fail. */
|
||||
void failDeadLetterPublish();
|
||||
|
||||
/** Makes the next publish be refused outright by the broker. */
|
||||
void rejectPublish();
|
||||
|
||||
/** Clears every injected fault. */
|
||||
void reset();
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
/** What the contract suite's handler decides for a drained delivery. */
|
||||
public enum HandleOutcome {
|
||||
|
||||
/** The handler succeeded and the platform may settle. */
|
||||
SUCCESS,
|
||||
|
||||
/** The handler failed transiently and the message should be retried. */
|
||||
RETRY,
|
||||
|
||||
/** The handler failed permanently and the message should be dead lettered. */
|
||||
DEAD_LETTER
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The behaviour every adapter must exhibit, regardless of broker.
|
||||
*
|
||||
* <p>This suite is the platform's actual definition of "supported". A broker is Stable when it
|
||||
* passes these unchanged — not when it has an adapter that compiles. Each test pins one of the
|
||||
* guarantees the design refuses to weaken: ambiguity is reported rather than guessed, settlement
|
||||
* follows handler success, logical identity survives retry and dead lettering, and a source is
|
||||
* never acknowledged on the strength of a dead letter publish that failed.
|
||||
*/
|
||||
public abstract class MessagingAdapterContract {
|
||||
|
||||
/**
|
||||
* Returns a fresh harness for one test.
|
||||
*
|
||||
* @return the adapter harness under test
|
||||
*/
|
||||
protected abstract MessagingAdapterHarness harness();
|
||||
|
||||
@Test
|
||||
void publishesAndConfirms() {
|
||||
try (MessagingAdapterHarness harness = harness()) {
|
||||
PublishResult result = join(harness.publish(ContractMessage.orderCreated()));
|
||||
|
||||
ContractAssertions.assertConfirmed(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsAmbiguousWhenConfirmIsLost() {
|
||||
try (MessagingAdapterHarness harness = harness()) {
|
||||
harness.faults().dropPublishConfirmation();
|
||||
|
||||
PublishResult result = join(harness.publish(ContractMessage.orderCreated()));
|
||||
|
||||
ContractAssertions.assertAmbiguous(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeliversWhenSettlementIsLost() {
|
||||
try (MessagingAdapterHarness harness = harness()) {
|
||||
ContractMessage message = ContractMessage.orderCreated();
|
||||
join(harness.publish(message));
|
||||
harness.faults().dropSettlementConfirmation();
|
||||
|
||||
List<ObservedDelivery> first = harness.drain(HandleOutcome.SUCCESS);
|
||||
assertThat(first)
|
||||
.singleElement()
|
||||
.satisfies(
|
||||
delivery -> {
|
||||
assertThat(delivery.messageId()).isEqualTo(message.messageId());
|
||||
assertThat(delivery.settled()).isFalse();
|
||||
});
|
||||
|
||||
List<ObservedDelivery> second = harness.drain(HandleOutcome.SUCCESS);
|
||||
assertThat(second)
|
||||
.singleElement()
|
||||
.satisfies(
|
||||
delivery -> {
|
||||
assertThat(delivery.messageId()).isEqualTo(message.messageId());
|
||||
assertThat(delivery.attempt()).isEqualTo(2);
|
||||
assertThat(delivery.redelivered()).isTrue();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesMessageIdAcrossRetryAndDlq() {
|
||||
try (MessagingAdapterHarness harness = harness()) {
|
||||
ContractMessage message = ContractMessage.orderCreated();
|
||||
join(harness.publish(message));
|
||||
MessageId original = message.messageId();
|
||||
|
||||
List<ObservedDelivery> retried = harness.drain(HandleOutcome.RETRY);
|
||||
assertThat(retried)
|
||||
.singleElement()
|
||||
.extracting(ObservedDelivery::messageId)
|
||||
.isEqualTo(original);
|
||||
|
||||
List<ObservedDelivery> redelivered = harness.drain(HandleOutcome.DEAD_LETTER);
|
||||
assertThat(redelivered)
|
||||
.singleElement()
|
||||
.extracting(ObservedDelivery::messageId)
|
||||
.isEqualTo(original);
|
||||
|
||||
assertThat(harness.deadLettered()).containsExactly(original);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsSourceUnsettledWhenDlqPublishFails() {
|
||||
try (MessagingAdapterHarness harness = harness()) {
|
||||
ContractMessage message = ContractMessage.orderCreated();
|
||||
join(harness.publish(message));
|
||||
harness.faults().failDeadLetterPublish();
|
||||
|
||||
List<ObservedDelivery> observed = harness.drain(HandleOutcome.DEAD_LETTER);
|
||||
|
||||
assertThat(observed).singleElement().extracting(ObservedDelivery::settled).isEqualTo(false);
|
||||
assertThat(harness.deadLettered()).isEmpty();
|
||||
assertThat(harness.unsettled()).contains(message.messageId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsOversizedPayloadBeforeTransport() {
|
||||
try (MessagingAdapterHarness harness = harness()) {
|
||||
PublishResult result = join(harness.publish(ContractMessage.oversized()));
|
||||
|
||||
ContractAssertions.assertRejectedLocally(result);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopsAcceptingNewWorkDuringShutdown() {
|
||||
try (MessagingAdapterHarness harness = harness()) {
|
||||
assertThat(harness.isAcceptingWork()).isTrue();
|
||||
|
||||
harness.beginShutdown();
|
||||
|
||||
assertThat(harness.isAcceptingWork()).isFalse();
|
||||
PublishResult result = join(harness.publish(ContractMessage.orderCreated()));
|
||||
ContractAssertions.assertRejectedLocally(result);
|
||||
}
|
||||
}
|
||||
|
||||
private static PublishResult join(java.util.concurrent.CompletionStage<PublishResult> stage) {
|
||||
return stage.toCompletableFuture().join();
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/**
|
||||
* The seam each broker adapter implements to run the common contract.
|
||||
*
|
||||
* <p>The harness exposes outcomes, not internals: what the platform decided, what reached the dead
|
||||
* letter destination, and what is still unsettled. Kafka and RabbitMQ answer those three questions
|
||||
* with completely different machinery, and the contract only passes if the answers match.
|
||||
*/
|
||||
public interface MessagingAdapterHarness extends AutoCloseable {
|
||||
|
||||
/**
|
||||
* Returns the broker under test.
|
||||
*
|
||||
* @return the broker name
|
||||
*/
|
||||
String brokerName();
|
||||
|
||||
/**
|
||||
* Returns the fault injector for this harness.
|
||||
*
|
||||
* @return the fault controller
|
||||
*/
|
||||
FaultController faults();
|
||||
|
||||
/**
|
||||
* Publishes one contract message.
|
||||
*
|
||||
* @param message the message to publish
|
||||
* @return a stage completing with the outcome and evidence
|
||||
*/
|
||||
CompletionStage<PublishResult> publish(ContractMessage message);
|
||||
|
||||
/**
|
||||
* Delivers everything currently pending to a handler that returns the given outcome.
|
||||
*
|
||||
* @param outcome what the handler decides for each delivery
|
||||
* @return what the harness observed, in delivery order
|
||||
*/
|
||||
List<ObservedDelivery> drain(HandleOutcome outcome);
|
||||
|
||||
/**
|
||||
* Returns the identities that reached the dead letter destination.
|
||||
*
|
||||
* @return dead lettered message identities
|
||||
*/
|
||||
List<MessageId> deadLettered();
|
||||
|
||||
/**
|
||||
* Returns the identities still unsettled at the source.
|
||||
*
|
||||
* @return unsettled message identities
|
||||
*/
|
||||
List<MessageId> unsettled();
|
||||
|
||||
/** Begins a graceful drain. */
|
||||
void beginShutdown();
|
||||
|
||||
/**
|
||||
* Reports whether the harness still accepts new work.
|
||||
*
|
||||
* @return true until shutdown begins
|
||||
*/
|
||||
boolean isAcceptingWork();
|
||||
|
||||
@Override
|
||||
void close();
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* A named network fault, and the outcome an adapter must report while it is active.
|
||||
*
|
||||
* <p>The expected outcome is part of the scenario rather than left to each test, because the whole
|
||||
* value of a fault suite is that every adapter answers the same way. A scenario that let each
|
||||
* adapter declare its own expectation would pass while the adapters disagreed — which is exactly
|
||||
* the situation the shared contract exists to catch.
|
||||
*
|
||||
* <p>The distinction across these scenarios is what evidence survives. A connection refused before
|
||||
* any bytes leave proves nothing was published; a connection cut after the frame was written proves
|
||||
* nothing at all, and the honest answer is ambiguous.
|
||||
*
|
||||
* @param name the scenario name, used in reports
|
||||
* @param phase when the fault is injected relative to the publish
|
||||
* @param expectation what the adapter must report
|
||||
* @param duration how long the fault holds, when it is time-bounded
|
||||
* @param rationale why this outcome is the correct one
|
||||
*/
|
||||
public record NetworkFaultScenario(
|
||||
String name,
|
||||
Phase phase,
|
||||
Expectation expectation,
|
||||
Optional<Duration> duration,
|
||||
String rationale) {
|
||||
|
||||
/** When a fault takes effect relative to the operation under test. */
|
||||
public enum Phase {
|
||||
/** Before any bytes leave the client. */
|
||||
BEFORE_TRANSMISSION,
|
||||
/** After the frame was written but before the acknowledgement. */
|
||||
AFTER_TRANSMISSION,
|
||||
/** While the consumer holds an unsettled delivery. */
|
||||
DURING_SETTLEMENT
|
||||
}
|
||||
|
||||
/** What the adapter must report under a fault. */
|
||||
public enum Expectation {
|
||||
/** A definite rejection, with no ambiguity. */
|
||||
REJECTED,
|
||||
/** An unknown outcome, reported as such rather than guessed. */
|
||||
AMBIGUOUS,
|
||||
/** The message is redelivered because it was never settled. */
|
||||
REDELIVERED
|
||||
}
|
||||
|
||||
public NetworkFaultScenario {
|
||||
Objects.requireNonNull(phase, "phase must not be null");
|
||||
Objects.requireNonNull(expectation, "expectation must not be null");
|
||||
Objects.requireNonNull(duration, "duration must not be null");
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new IllegalArgumentException("name must not be blank");
|
||||
}
|
||||
if (rationale == null || rationale.isBlank()) {
|
||||
throw new IllegalArgumentException(
|
||||
"a scenario without a rationale cannot be reviewed; state why this outcome is correct");
|
||||
}
|
||||
}
|
||||
|
||||
/** The connection is refused before the publish frame is written. */
|
||||
public static final NetworkFaultScenario CONNECTION_REFUSED =
|
||||
new NetworkFaultScenario(
|
||||
"connection-refused",
|
||||
Phase.BEFORE_TRANSMISSION,
|
||||
Expectation.REJECTED,
|
||||
Optional.empty(),
|
||||
"no bytes left the client, so the broker cannot hold the message and a retry cannot "
|
||||
+ "duplicate it");
|
||||
|
||||
/** The connection is cut after the frame is written but before the confirm. */
|
||||
public static final NetworkFaultScenario CONNECTION_CUT_AFTER_WRITE =
|
||||
new NetworkFaultScenario(
|
||||
"connection-cut-after-write",
|
||||
Phase.AFTER_TRANSMISSION,
|
||||
Expectation.AMBIGUOUS,
|
||||
Optional.empty(),
|
||||
"the broker may have stored the message and only the confirm was lost; reporting a "
|
||||
+ "rejection here is what turns one lost confirmation into two orders");
|
||||
|
||||
/** The confirm is delayed past the publish deadline. */
|
||||
public static final NetworkFaultScenario CONFIRM_TIMEOUT =
|
||||
new NetworkFaultScenario(
|
||||
"confirm-timeout",
|
||||
Phase.AFTER_TRANSMISSION,
|
||||
Expectation.AMBIGUOUS,
|
||||
Optional.of(Duration.ofSeconds(10)),
|
||||
"a timeout is the absence of evidence, not evidence of absence");
|
||||
|
||||
/** The broker becomes unreachable while a delivery is unsettled. */
|
||||
public static final NetworkFaultScenario SETTLEMENT_LOST =
|
||||
new NetworkFaultScenario(
|
||||
"settlement-lost",
|
||||
Phase.DURING_SETTLEMENT,
|
||||
Expectation.REDELIVERED,
|
||||
Optional.empty(),
|
||||
"an unsettled delivery is redelivered by design; the handler must be idempotent rather "
|
||||
+ "than the platform pretending the settlement landed");
|
||||
|
||||
/** High latency without a disconnect, which slows confirms without losing them. */
|
||||
public static final NetworkFaultScenario HIGH_LATENCY =
|
||||
new NetworkFaultScenario(
|
||||
"high-latency",
|
||||
Phase.AFTER_TRANSMISSION,
|
||||
Expectation.AMBIGUOUS,
|
||||
Optional.of(Duration.ofSeconds(30)),
|
||||
"latency above the publish deadline is indistinguishable from a lost confirm at the "
|
||||
+ "moment the decision has to be made");
|
||||
|
||||
/**
|
||||
* Returns every scenario the shared fault suite runs.
|
||||
*
|
||||
* @return the scenarios
|
||||
*/
|
||||
public static java.util.List<NetworkFaultScenario> all() {
|
||||
return java.util.List.of(
|
||||
CONNECTION_REFUSED,
|
||||
CONNECTION_CUT_AFTER_WRITE,
|
||||
CONFIRM_TIMEOUT,
|
||||
SETTLEMENT_LOST,
|
||||
HIGH_LATENCY);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* What the harness observed about one delivery attempt.
|
||||
*
|
||||
* @param messageId the logical identity delivered
|
||||
* @param attempt the attempt number, counting the first delivery as one
|
||||
* @param redelivered whether the broker flagged this as a redelivery
|
||||
* @param settled whether the source was settled after handling
|
||||
*/
|
||||
public record ObservedDelivery(
|
||||
MessageId messageId, int attempt, boolean redelivered, boolean settled) {
|
||||
|
||||
public ObservedDelivery {
|
||||
Objects.requireNonNull(messageId, "messageId must not be null");
|
||||
if (attempt < 1) {
|
||||
throw new IllegalArgumentException("attempt counts the first delivery as 1");
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CompatibilityMatrixTest {
|
||||
|
||||
private static final List<String> REQUIRED_CONTRACT_TESTS =
|
||||
List.of(
|
||||
"publishesAndConfirms",
|
||||
"returnsAmbiguousWhenConfirmIsLost",
|
||||
"redeliversWhenSettlementIsLost",
|
||||
"preservesMessageIdAcrossRetryAndDlq",
|
||||
"keepsSourceUnsettledWhenDlqPublishFails",
|
||||
"rejectsOversizedPayloadBeforeTransport",
|
||||
"stopsAcceptingNewWorkDuringShutdown");
|
||||
|
||||
@Test
|
||||
void everyStableAdapterRunsTheSharedContract() {
|
||||
assertThat(CompatibilityMatrix.entries().values())
|
||||
.filteredOn(entry -> entry.tier() == CompatibilityMatrix.Tier.STABLE)
|
||||
.isNotEmpty()
|
||||
.allSatisfy(entry -> assertThat(entry.runsSharedContract()).isTrue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noExperimentalAdapterIsEnabledByDefault() {
|
||||
assertThat(CompatibilityMatrix.entries().values())
|
||||
.filteredOn(entry -> entry.tier() == CompatibilityMatrix.Tier.EXPERIMENTAL)
|
||||
.isNotEmpty()
|
||||
.allSatisfy(entry -> assertThat(entry.enabledByDefault()).isFalse());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theStableSetIsExactlyKafkaAndRabbit() {
|
||||
assertThat(CompatibilityMatrix.entries().values())
|
||||
.filteredOn(entry -> entry.tier() == CompatibilityMatrix.Tier.STABLE)
|
||||
.extracting(CompatibilityMatrix.Entry::adapter)
|
||||
.containsExactlyInAnyOrder("messaging-kafka", "messaging-rabbit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void kafkaIsCertifiedAgainstFourTwoAndFourThree() {
|
||||
assertThat(CompatibilityMatrix.of("messaging-kafka").brokerVersions())
|
||||
.containsExactly("4.2", "4.3");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSharedContractStillDeclaresEveryRequiredTest() {
|
||||
List<String> declared =
|
||||
Arrays.stream(MessagingAdapterContract.class.getDeclaredMethods())
|
||||
.filter(method -> method.isAnnotationPresent(org.junit.jupiter.api.Test.class))
|
||||
.map(Method::getName)
|
||||
.toList();
|
||||
|
||||
assertThat(declared).containsExactlyInAnyOrderElementsOf(REQUIRED_CONTRACT_TESTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownAdapterIsNotSilentlyTreatedAsSupported() {
|
||||
assertThatThrownBy(() -> CompatibilityMatrix.of("messaging-artemis"))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAdapterMustCertifyAtLeastOneBrokerVersion() {
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
new CompatibilityMatrix.Entry(
|
||||
"messaging-x", List.of(), CompatibilityMatrix.Tier.STABLE, true, true, true))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyStableAdapterIsCertifiedAgainstALiveBroker() {
|
||||
assertThat(CompatibilityMatrix.entries().values())
|
||||
.filteredOn(entry -> entry.tier() == CompatibilityMatrix.Tier.STABLE)
|
||||
.isNotEmpty()
|
||||
.allSatisfy(
|
||||
entry ->
|
||||
assertThat(entry.hasLiveBrokerCertification())
|
||||
.as(
|
||||
"%s claims Stable, so a container-backed suite must exercise a real broker",
|
||||
entry.adapter())
|
||||
.isTrue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noExperimentalAdapterClaimsLiveBrokerCertification() {
|
||||
assertThat(CompatibilityMatrix.entries().values())
|
||||
.filteredOn(entry -> entry.tier() == CompatibilityMatrix.Tier.EXPERIMENTAL)
|
||||
.allSatisfy(entry -> assertThat(entry.hasLiveBrokerCertification()).isFalse());
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.messaging.testkit.BrokerFailureMatrix.Coverage;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* The release gate over the whole adapter set.
|
||||
*
|
||||
* <p>Every other suite proves one adapter behaves correctly. This one proves the adapters agree —
|
||||
* that the same fault produces the same reported outcome whichever broker is underneath, and that
|
||||
* nothing has been promoted to Stable without the evidence that tier claims.
|
||||
*
|
||||
* <p>It asserts on the coverage records rather than re-running the fault suites, because it is the
|
||||
* <em>bookkeeping</em> that rots: an adapter's own tests keep passing while the matrix quietly
|
||||
* stops reflecting what was actually run.
|
||||
*/
|
||||
class CrossBrokerContractSuite {
|
||||
|
||||
private final BrokerFailureMatrix matrix = BrokerFailureMatrix.shipped();
|
||||
|
||||
private static List<String> stableAdapters() {
|
||||
return CompatibilityMatrix.entries().values().stream()
|
||||
.filter(entry -> entry.tier() == CompatibilityMatrix.Tier.STABLE)
|
||||
.map(CompatibilityMatrix.Entry::adapter)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyStableAdapterCoversEveryFaultScenario() {
|
||||
assertThat(stableAdapters())
|
||||
.isNotEmpty()
|
||||
.allSatisfy(
|
||||
adapter ->
|
||||
assertThat(matrix.gapsFor(adapter))
|
||||
.as("%s is Stable, so no fault scenario may be unrun", adapter)
|
||||
.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyStableAdapterCoversTheFaultsAgainstALiveBroker() {
|
||||
assertThat(stableAdapters())
|
||||
.allSatisfy(
|
||||
adapter ->
|
||||
assertThat(NetworkFaultScenario.all())
|
||||
.allSatisfy(
|
||||
scenario ->
|
||||
assertThat(matrix.coverageOf(adapter, scenario))
|
||||
.as("%s / %s", adapter, scenario.name())
|
||||
.isEqualTo(Coverage.LIVE_BROKER)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noExperimentalAdapterClaimsLiveBrokerFaultCoverage() {
|
||||
List<String> experimental =
|
||||
CompatibilityMatrix.entries().values().stream()
|
||||
.filter(entry -> entry.tier() == CompatibilityMatrix.Tier.EXPERIMENTAL)
|
||||
.map(CompatibilityMatrix.Entry::adapter)
|
||||
.toList();
|
||||
|
||||
assertThat(experimental)
|
||||
.allSatisfy(
|
||||
adapter ->
|
||||
assertThat(NetworkFaultScenario.all())
|
||||
.allSatisfy(
|
||||
scenario ->
|
||||
assertThat(matrix.coverageOf(adapter, scenario))
|
||||
.isNotEqualTo(Coverage.LIVE_BROKER)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExperimentalAdapterIsAllowedGapsButTheyAreRecorded() {
|
||||
assertThat(matrix.isComplete("messaging-pulsar-experimental"))
|
||||
.as("the Experimental tier is a statement of fact, not a disclaimer")
|
||||
.isFalse();
|
||||
assertThat(matrix.gapsFor("messaging-pulsar-experimental")).isNotEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFaultThatWasNeverRecordedReadsAsUncoveredRatherThanPassing() {
|
||||
assertThat(matrix.coverageOf("messaging-artemis", NetworkFaultScenario.CONFIRM_TIMEOUT))
|
||||
.isEqualTo(Coverage.NOT_COVERED);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyAdapterAgreesThatAWriteFollowedByALostConfirmIsAmbiguous() {
|
||||
assertThat(NetworkFaultScenario.CONNECTION_CUT_AFTER_WRITE.expectation())
|
||||
.as("the shared expectation is what stops two adapters answering differently")
|
||||
.isEqualTo(NetworkFaultScenario.Expectation.AMBIGUOUS);
|
||||
assertThat(NetworkFaultScenario.CONFIRM_TIMEOUT.expectation())
|
||||
.isEqualTo(NetworkFaultScenario.Expectation.AMBIGUOUS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailureBeforeTransmissionIsTheOnlyOneReportedAsRejected() {
|
||||
assertThat(NetworkFaultScenario.all())
|
||||
.filteredOn(scenario -> scenario.expectation() == NetworkFaultScenario.Expectation.REJECTED)
|
||||
.allSatisfy(
|
||||
scenario ->
|
||||
assertThat(scenario.phase())
|
||||
.isEqualTo(NetworkFaultScenario.Phase.BEFORE_TRANSMISSION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyScenarioStatesWhyItsOutcomeIsCorrect() {
|
||||
assertThat(NetworkFaultScenario.all())
|
||||
.allSatisfy(scenario -> assertThat(scenario.rationale()).isNotBlank());
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import org.junit.jupiter.api.Nested;
|
||||
|
||||
/**
|
||||
* Runs the shared adapter contract against the in-memory harness.
|
||||
*
|
||||
* <p>This is the contract testing itself. Every broker adapter adds the same nested class over its
|
||||
* own harness, so a guarantee can only be weakened by editing the contract, where the change is
|
||||
* visible, rather than by an adapter quietly not implementing it.
|
||||
*/
|
||||
class InMemoryHarnessContractTest {
|
||||
|
||||
@Nested
|
||||
class Contract extends MessagingAdapterContract {
|
||||
|
||||
@Override
|
||||
protected MessagingAdapterHarness harness() {
|
||||
return InMemoryMessagingHarness.create();
|
||||
}
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.error.FailureCategory;
|
||||
import dev.caskeleton.messaging.api.error.FailureDescriptor;
|
||||
import dev.caskeleton.messaging.api.publish.ConfirmationLevel;
|
||||
import dev.caskeleton.messaging.api.publish.PublishCompletion;
|
||||
import dev.caskeleton.messaging.api.publish.PublishEvidence;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import dev.caskeleton.messaging.api.publish.RoutingOutcome;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
|
||||
/**
|
||||
* A deterministic harness that exists only to prove the contract suite itself is sound.
|
||||
*
|
||||
* <p>It is not a production adapter and must never become one. Its value is that it has no broker
|
||||
* to hide behind: if a contract test passes here and fails on Kafka, the difference is in the
|
||||
* adapter, not in the test.
|
||||
*/
|
||||
final class InMemoryMessagingHarness implements MessagingAdapterHarness {
|
||||
|
||||
private static final int MAX_PAYLOAD_BYTES = 1_048_576;
|
||||
|
||||
private final Deque<Pending> pending = new ArrayDeque<>();
|
||||
private final List<MessageId> deadLetters = new ArrayList<>();
|
||||
private final Set<MessageId> unsettled = new LinkedHashSet<>();
|
||||
private final Faults faults = new Faults();
|
||||
|
||||
private boolean shuttingDown;
|
||||
|
||||
private InMemoryMessagingHarness() {}
|
||||
|
||||
static InMemoryMessagingHarness create() {
|
||||
return new InMemoryMessagingHarness();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String brokerName() {
|
||||
return "in-memory";
|
||||
}
|
||||
|
||||
@Override
|
||||
public FaultController faults() {
|
||||
return faults;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletionStage<PublishResult> publish(ContractMessage message) {
|
||||
if (shuttingDown) {
|
||||
return completed(
|
||||
rejected("SHUTTING_DOWN", "the consumer is draining and accepts no new work"));
|
||||
}
|
||||
if (message.envelope().payload().size() > MAX_PAYLOAD_BYTES) {
|
||||
return completed(
|
||||
rejected("PAYLOAD_TOO_LARGE", "encoded payload exceeds " + MAX_PAYLOAD_BYTES + " bytes"));
|
||||
}
|
||||
if (faults.consumeRejectPublish()) {
|
||||
return completed(rejected("BROKER_REJECTED", "the broker refused the publish"));
|
||||
}
|
||||
|
||||
if (faults.consumeDropPublishConfirmation()) {
|
||||
return completed(
|
||||
new PublishResult(
|
||||
PublishCompletion.AMBIGUOUS,
|
||||
PublishEvidence.ambiguous(),
|
||||
RoutingOutcome.UNKNOWN,
|
||||
Optional.empty(),
|
||||
1,
|
||||
Duration.ofMillis(1),
|
||||
Optional.of(
|
||||
FailureDescriptor.of(
|
||||
FailureCategory.AMBIGUOUS,
|
||||
"CONFIRM_LOST",
|
||||
"the publish confirmation was not received"))));
|
||||
}
|
||||
|
||||
pending.addLast(new Pending(message.messageId(), 1, false));
|
||||
return completed(
|
||||
new PublishResult(
|
||||
PublishCompletion.CONFIRMED,
|
||||
PublishEvidence.confirmed(ConfirmationLevel.REPLICATION_OR_PERSISTENCE_ACK),
|
||||
RoutingOutcome.ROUTED,
|
||||
Optional.empty(),
|
||||
1,
|
||||
Duration.ofMillis(1),
|
||||
Optional.empty()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ObservedDelivery> drain(HandleOutcome outcome) {
|
||||
List<Pending> batch = new ArrayList<>(pending);
|
||||
pending.clear();
|
||||
|
||||
List<ObservedDelivery> observed = new ArrayList<>();
|
||||
for (Pending delivery : batch) {
|
||||
boolean settled =
|
||||
switch (outcome) {
|
||||
case SUCCESS -> settleAfterSuccess(delivery);
|
||||
case RETRY -> {
|
||||
unsettled.add(delivery.messageId());
|
||||
redeliver(delivery);
|
||||
yield false;
|
||||
}
|
||||
case DEAD_LETTER -> deadLetter(delivery);
|
||||
};
|
||||
observed.add(
|
||||
new ObservedDelivery(
|
||||
delivery.messageId(), delivery.attempt(), delivery.redelivered(), settled));
|
||||
}
|
||||
return List.copyOf(observed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Settles the source only when the settlement itself was confirmed.
|
||||
*
|
||||
* <p>An unconfirmed settlement leaves the message in flight, which is what produces the
|
||||
* redelivery the contract expects.
|
||||
*/
|
||||
private boolean settleAfterSuccess(Pending delivery) {
|
||||
if (faults.consumeDropSettlementConfirmation()) {
|
||||
unsettled.add(delivery.messageId());
|
||||
redeliver(delivery);
|
||||
return false;
|
||||
}
|
||||
unsettled.remove(delivery.messageId());
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes to the dead letter destination before settling the source.
|
||||
*
|
||||
* <p>When that publish fails the source stays unsettled and in flight. Acknowledging it here
|
||||
* would destroy the last copy of a message the dead letter destination never received.
|
||||
*/
|
||||
private boolean deadLetter(Pending delivery) {
|
||||
if (faults.deadLetterPublishFails()) {
|
||||
unsettled.add(delivery.messageId());
|
||||
redeliver(delivery);
|
||||
return false;
|
||||
}
|
||||
deadLetters.add(delivery.messageId());
|
||||
unsettled.remove(delivery.messageId());
|
||||
return true;
|
||||
}
|
||||
|
||||
private void redeliver(Pending delivery) {
|
||||
pending.addLast(new Pending(delivery.messageId(), delivery.attempt() + 1, true));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MessageId> deadLettered() {
|
||||
return List.copyOf(deadLetters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MessageId> unsettled() {
|
||||
return List.copyOf(unsettled);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void beginShutdown() {
|
||||
shuttingDown = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAcceptingWork() {
|
||||
return !shuttingDown;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
pending.clear();
|
||||
}
|
||||
|
||||
private static PublishResult rejected(String code, String message) {
|
||||
return new PublishResult(
|
||||
PublishCompletion.REJECTED,
|
||||
PublishEvidence.notTransmitted(),
|
||||
RoutingOutcome.NOT_APPLICABLE,
|
||||
Optional.empty(),
|
||||
1,
|
||||
Duration.ZERO,
|
||||
Optional.of(FailureDescriptor.of(FailureCategory.PERMANENT_BUSINESS, code, message)));
|
||||
}
|
||||
|
||||
private static CompletionStage<PublishResult> completed(PublishResult result) {
|
||||
return CompletableFuture.completedFuture(result);
|
||||
}
|
||||
|
||||
/** One message waiting to be delivered. */
|
||||
private record Pending(MessageId messageId, int attempt, boolean redelivered) {}
|
||||
|
||||
/** One-shot fault flags, consumed by the operation they target. */
|
||||
private static final class Faults implements FaultController {
|
||||
|
||||
private boolean dropPublishConfirmation;
|
||||
private boolean dropSettlementConfirmation;
|
||||
private boolean failDeadLetterPublish;
|
||||
private boolean rejectPublish;
|
||||
|
||||
@Override
|
||||
public void dropPublishConfirmation() {
|
||||
dropPublishConfirmation = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void dropSettlementConfirmation() {
|
||||
dropSettlementConfirmation = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failDeadLetterPublish() {
|
||||
failDeadLetterPublish = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void rejectPublish() {
|
||||
rejectPublish = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void reset() {
|
||||
dropPublishConfirmation = false;
|
||||
dropSettlementConfirmation = false;
|
||||
failDeadLetterPublish = false;
|
||||
rejectPublish = false;
|
||||
}
|
||||
|
||||
boolean consumeDropPublishConfirmation() {
|
||||
boolean active = dropPublishConfirmation;
|
||||
dropPublishConfirmation = false;
|
||||
return active;
|
||||
}
|
||||
|
||||
boolean consumeDropSettlementConfirmation() {
|
||||
boolean active = dropSettlementConfirmation;
|
||||
dropSettlementConfirmation = false;
|
||||
return active;
|
||||
}
|
||||
|
||||
boolean consumeRejectPublish() {
|
||||
boolean active = rejectPublish;
|
||||
rejectPublish = false;
|
||||
return active;
|
||||
}
|
||||
|
||||
boolean deadLetterPublishFails() {
|
||||
return failDeadLetterPublish;
|
||||
}
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
package dev.caskeleton.messaging.testkit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Checks that the shipped documentation still describes the code.
|
||||
*
|
||||
* <p>Docs rot silently. A support matrix claiming an adapter is Stable outlives the day someone
|
||||
* demoted it, and nothing fails — the tests still pass, the build is green, and the only signal is
|
||||
* an operator making a decision on a page that stopped being true months ago.
|
||||
*
|
||||
* <p>The assertions are deliberately narrow: they check the claims a reader would act on, not
|
||||
* prose. Asserting on wording would make every edit a test failure and the check would be deleted.
|
||||
*/
|
||||
class MessagingDocumentationContractTest {
|
||||
|
||||
private static Path docsRoot() {
|
||||
Path candidate = Path.of("").toAbsolutePath();
|
||||
while (candidate != null && !Files.isDirectory(candidate.resolve("docs/messaging"))) {
|
||||
candidate = candidate.getParent();
|
||||
}
|
||||
if (candidate == null) {
|
||||
throw new IllegalStateException("could not locate docs/messaging from the test cwd");
|
||||
}
|
||||
return candidate.resolve("docs/messaging");
|
||||
}
|
||||
|
||||
private static String read(String name) {
|
||||
try {
|
||||
return Files.readString(docsRoot().resolve(name));
|
||||
} catch (IOException failure) {
|
||||
throw new IllegalStateException("could not read " + name, failure);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDocumentTheSupportMatrixPromisesExists() {
|
||||
List<String> expected =
|
||||
List.of(
|
||||
"support-matrix.md",
|
||||
"delivery-guarantees.md",
|
||||
"retry-dlq-redrive.md",
|
||||
"outbox-inbox.md",
|
||||
"security.md",
|
||||
"operations.md",
|
||||
"configuration-reference.md",
|
||||
"experimental-policy.md",
|
||||
"migration-guide.md");
|
||||
|
||||
assertThat(expected)
|
||||
.allSatisfy(name -> assertThat(Files.exists(docsRoot().resolve(name))).isTrue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSupportMatrixNamesExactlyTheAdaptersTheCodeCallsStable() {
|
||||
String matrix = read("support-matrix.md");
|
||||
|
||||
CompatibilityMatrix.entries().values().stream()
|
||||
.filter(entry -> entry.tier() == CompatibilityMatrix.Tier.STABLE)
|
||||
.forEach(entry -> assertThat(matrix).contains(brokerLabel(entry.adapter())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSupportMatrixDoesNotCallAnExperimentalAdapterStable() {
|
||||
String matrix = read("support-matrix.md");
|
||||
|
||||
CompatibilityMatrix.entries().values().stream()
|
||||
.filter(entry -> entry.tier() == CompatibilityMatrix.Tier.EXPERIMENTAL)
|
||||
.forEach(
|
||||
entry ->
|
||||
assertThat(matrix)
|
||||
.as("%s is Experimental in code", entry.adapter())
|
||||
.doesNotContain("| %s | Stable".formatted(brokerLabel(entry.adapter()))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDocumentedKafkaVersionsMatchWhatTheCodeCertifies() {
|
||||
String matrix = read("support-matrix.md");
|
||||
|
||||
CompatibilityMatrix.of("messaging-kafka")
|
||||
.brokerVersions()
|
||||
.forEach(version -> assertThat(matrix).contains(version));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theUnsupportedListStillNamesTheTwoConstantsThatDoNotExist() {
|
||||
String matrix = read("support-matrix.md");
|
||||
|
||||
assertThat(matrix)
|
||||
.as("a reader must be able to confirm the platform never offers these")
|
||||
.contains("EXACTLY_ONCE")
|
||||
.contains("GLOBAL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void noEnumConstantTheDocsDenyActuallyExists() {
|
||||
assertThat(
|
||||
java.util.Arrays.stream(
|
||||
dev.caskeleton.messaging.api.delivery.DeliveryGuarantee.values())
|
||||
.map(Enum::name))
|
||||
.doesNotContain("EXACTLY_ONCE");
|
||||
assertThat(
|
||||
java.util.Arrays.stream(dev.caskeleton.messaging.api.delivery.OrderingScope.values())
|
||||
.map(Enum::name))
|
||||
.doesNotContain("GLOBAL");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExperimentalPolicyStatesThatExperimentalIsOffByDefault() {
|
||||
assertThat(read("experimental-policy.md")).contains("false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDocumentHasContent() {
|
||||
assertThat(
|
||||
List.of(
|
||||
"support-matrix.md",
|
||||
"delivery-guarantees.md",
|
||||
"retry-dlq-redrive.md",
|
||||
"outbox-inbox.md",
|
||||
"security.md",
|
||||
"operations.md",
|
||||
"configuration-reference.md",
|
||||
"experimental-policy.md",
|
||||
"migration-guide.md"))
|
||||
.allSatisfy(name -> assertThat(read(name).length()).isGreaterThan(500));
|
||||
}
|
||||
|
||||
private static String brokerLabel(String adapter) {
|
||||
return switch (adapter) {
|
||||
case "messaging-kafka" -> "Kafka";
|
||||
case "messaging-rabbit" -> "RabbitMQ";
|
||||
case "messaging-pulsar-experimental" -> "Pulsar";
|
||||
case "messaging-nats-experimental" -> "NATS";
|
||||
case "messaging-kafka-share-experimental" -> "Kafka Share";
|
||||
default -> adapter;
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user