review-followup Wave 3 라운드 2(P18): outbox canonical 통일, composition 모듈, legacy Kafka seam 삭제

- 결정 7: `LegacyOutboxAppendPort`·legacy 저장 모델·relay·Kafka R0 seam 삭제, 템플릿 JSON encoder(`JsonIntegrationEventEncoder`),
  durable operation·sample 이벤트가 `OutboxAppendPort` + encoder로, persistence-jpa V19(pre-canonical 미발행 row 거부)
- 결정 3: outbox relay·멱등성 executor 조립을 `composition:outbox-relay`·`composition:idempotency`로,
  sample이 복사한 bootstrap 인프라를 `composition:service-runtime`으로(sample `SampleIdempotencyConfig` 복사본 삭제)
- persistence-jpa outbox·멱등성 패키지 feature 기준 이동, messaging outbox·inbox leaf를 reliability / reliability-jdbc-postgresql로
- messaging outbox header를 jsonb로(P18-new-1 — `\`로 끝나는 값이 다음 header를 삼키던 결함)
- 통합(충돌 22건): P25 A-10c(전략 선택 설정 삭제)를 service-runtime `DomainContextConfig`에 적용, P25 startup 예외 통합을
  composition 설정 테스트에, P25 `CommandUseCase.handle` 이름을 PG 통합 테스트에, P15 `EventJson`은 호출자 0이 되어 삭제
- root CLAUDE.md의 legacy seam 문장 수정(P18-new-2)

검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys
configContractCheck :app-bootstrap:integrationTest :sample-portfolio:integrationTest :sample-portfolio:systemTest
persistence-jpa jpaPlatformContractTest·postgresql{Idempotency,OutboxAppendTransactional,OutboxConcurrentRelay,OutboxRowLifecycle}IntegrationTest
:messaging:messaging-reliability-jdbc-postgresql:integrationTest --continue 통과(700 task)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-29 12:30:01 +09:00
co-authored by Claude Opus 5.5
parent 25de288ab4
commit 423a29c46f
329 changed files with 6380 additions and 6850 deletions
-1
View File
@@ -295,7 +295,6 @@ APP_WEBSOCKET_BROADCAST_DESTINATION=/topic/events
APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY=10000
APP_OUTBOX_ENABLED=false
APP_OUTBOX_RELAY_ENABLED=false
APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED=false
APP_NOTIFICATION_PLATFORM_ENABLED=true
APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE=ko-KR
APP_NOTIFICATION_PLATFORM_MODE=SERVING
+4 -4
View File
@@ -263,7 +263,7 @@ Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle`
|---|---|---|---|
| JPA/PostgreSQL (Flyway·outbox store·JDBC 멱등성·분산 락) | `runtimeOnly project(':adapter:outbound:persistence-jpa')` | `APP_DATASOURCE_URL`, `APP_DATASOURCE_USERNAME`, `APP_DATASOURCE_PASSWORD` | `APP_PERSISTENCE_JPA_ENABLED` |
| Redis (cache·rate limit·lease·멱등성) | `runtimeOnly project(':adapter:outbound:cache-redis')` | `APP_REDIS_MODE`, `APP_REDIS_NODES`, `APP_REDIS_NAMESPACE_*`, `APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE`, 쓰는 역할의 선택자(`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`, `APP_RATE_LIMIT_PROVIDER`, `APP_LEASE_PROVIDER`, `APP_IDEMPOTENCY_PROVIDER=redis`) | `APP_REDIS_ENABLED` |
| Kafka 발행 | `runtimeOnly project(':adapter:outbound:messaging-kafka')` | `APP_MESSAGING_KAFKA_BROKERS` (canonical 이벤트를 보내면 `APP_MESSAGING_PRODUCER_ID`) | `APP_MESSAGING_ENABLED` |
| Kafka 발행 | `runtimeOnly project(':adapter:outbound:messaging-kafka')` | `APP_MESSAGING_KAFKA_BROKERS`, `APP_MESSAGING_PRODUCER_ID` | `APP_MESSAGING_ENABLED` |
| Mongo | `runtimeOnly project(':adapter:outbound:persistence-mongo')` | `APP_PERSISTENCE_MONGO_ACTIVE_PROFILE`, `SPRING_MONGODB_URI`(또는 profile의 `uri-secret`) | `APP_PERSISTENCE_MONGO_ENABLED` |
| GraphQL | `runtimeOnly project(':adapter:inbound:graphql')` | `APP_GRAPHQL_DEPLOYMENT_MODE` (local→`LOCAL`, dev→`DEV`, prod→`PRODUCTION_*`) | `APP_GRAPHQL_ENABLED` |
| 외부 HTTP 호출 | `runtimeOnly project(':adapter:outbound:httpclient')` | client 하나 이상: `APP_HTTPCLIENT_CLIENTS_0_*` (`docs/httpclient/env-fields.yaml`) | `APP_HTTPCLIENT_ENABLED` |
@@ -325,9 +325,9 @@ Kafka·Redis는 위 "기능 추가 = 한 줄 + env" 표의 한 줄로 고릅니
- **`APP_MESSAGING_BROKER`** — 활성 메시지 브로커 id. Kafka 모듈의 설정 기본값이 `kafka`(등록된 유일한
broker)라 보통 비워 두지 않습니다. 빈 값을 주면 기동이 거부되면서 이 키 이름을 지목합니다. 이 키를 비워도 메시징이 꺼지지는
않습니다 — 끄는 것은 `APP_MESSAGING_ENABLED=false`입니다.
- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. Kafka 모듈을 고르면 필수. legacy seam과
messaging platform의 Kafka transport(`app.messaging.brokers.kafka.bootstrap-servers`)가 같은 값을
씁니다. `spring.kafka.bootstrap-servers`는 읽지 않습니다.
- **`APP_MESSAGING_KAFKA_BROKERS`** — `host:port` CSV. Kafka 모듈을 고르면 필수. messaging
platform의 Kafka transport(`app.messaging.brokers.kafka.bootstrap-servers`)가 이 값을 씁니다.
`spring.kafka.bootstrap-servers`는 읽지 않습니다.
- **`APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED`** — Slack webhook R0 provider enable flag. notification 플랫폼이
켜졌을 때 어떤 provider를 쓸지 고르는 값입니다.
- **`APP_NOTIFICATION_GOOGLE_EMAIL_ENABLED`** — Google Email R0 provider enable flag. 위와 같습니다.
@@ -87,7 +87,6 @@ public class DurableOperationController {
null,
RequestFingerprint.ofSha256(payload.getBytes(StandardCharsets.UTF_8)),
payload,
OperationCommand.SUBMITTED_EVENT_TYPE,
OperationCommand.DEFAULT_TIME_TO_LIVE));
URI location =
ServletUriComponentsBuilder.fromCurrentRequestUri()
@@ -12,9 +12,10 @@ import com.jayway.jsonpath.JsonPath;
import dev.caskeleton.adapter.inbound.web.auth.AuthenticatedPrincipal;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.operation.CancelDurableOperationUseCase;
import dev.caskeleton.application.operation.DurableOperationSubmittedContract;
import dev.caskeleton.application.operation.GetDurableOperationUseCase;
import dev.caskeleton.application.operation.OperationCommand;
import dev.caskeleton.application.operation.SubmitDurableOperationUseCase;
import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStore;
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
@@ -60,7 +61,8 @@ class DurableOperationControllerTest {
void setUp() {
DurableOperationController controller =
new DurableOperationController(
new SubmitDurableOperationUseCase(operations, outbox, transactions, clock),
new SubmitDurableOperationUseCase(
operations, outbox, new FakeIntegrationEventEncoder(), transactions, clock),
new GetDurableOperationUseCase(operations, transactions, clock),
new CancelDurableOperationUseCase(operations, transactions, clock));
mvc =
@@ -121,7 +123,7 @@ class DurableOperationControllerTest {
// then
assertThat(outbox.oldestUnpublishedAgeSecondsByEventType(clock.instant()))
.containsOnlyKeys(OperationCommand.SUBMITTED_EVENT_TYPE);
.containsOnlyKeys(DurableOperationSubmittedContract.CONTRACT_ID.value());
}
@Test
+19 -13
View File
@@ -2,35 +2,40 @@
- Module ID: `adapter-outbound-messaging-kafka`
- Gradle path: `:adapter:outbound:messaging-kafka`
- Package: `dev.caskeleton.adapter.outbound.messaging.kafka`
- Package: `dev.caskeleton.adapter.outbound.messaging.kafka` (테스트만 있다)
- 테스트: `./gradlew :adapter:outbound:messaging-kafka:test --console=plain`
## 제공하는 것
이 모듈 하나를 붙이면 Kafka 발행이 들어온다. 유스케이스는 application-core 포트만 호출한다.
이 leaf에는 코드가 없다. 선택 한 줄과 설정 기본값을 묶는 capability 단위다.
```
adapter:outbound:messaging-kafka
├─ LegacyKafkaMessagingRootAutoConfiguration KafkaSender seam + KafkaMessageBroker
├─ config/module-defaults/messaging.yml (설정 기본값, support 로더가 읽음)
├─ adapter:outbound:messaging MessagePublisher, OutboxMessagePublishPort,
├─ adapter:outbound:messaging OutboxMessagePublishPort,
│ IntegrationEventPublishPort bridge
└─ messaging:messaging-spring-boot-starter-kafka messaging platform + Kafka transport
```
| 포트 (application-core) | 구현 |
| --- | --- |
| `OutboxMessagePublishPort` | legacy outbox row → `KafkaMessageBroker`, canonical row → `IntegrationEventPublishPort` |
| `IntegrationEventPublishPort` | platform `EncodedMessagePublisher` (`APP_MESSAGING_PRODUCER_ID`가 있을 때만) |
| `OutboxMessagePublishPort` | claim된 row의 validated event → `IntegrationEventPublishPort` |
| `IntegrationEventPublishPort` | platform `EncodedMessagePublisher` |
| `OutboxRelayFailureReportPort` | 구조화 로그 |
- 켜기와 끄기: 모듈이 있으면 켜진다. `APP_MESSAGING_ENABLED=false`로만 끈다. 끄면 messaging bean,
Kafka producer, 스레드가 하나도 생기지 않는다.
- 설정: `config/module-defaults/messaging.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가 읽는다. 우선순위가 가장 낮아서 `application*.yml`,
환경 변수, 시스템 속성이 항상 이긴다. app-bootstrap은 이 파일을 모른다.
- broker 주소 하나(`APP_MESSAGING_KAFKA_BROKERS`)가 legacy seam(`app.messaging.kafka.brokers`)과
platform transport(`app.messaging.brokers.kafka.bootstrap-servers`) 양쪽에 들어간다.
`spring.kafka.bootstrap-servers`는 읽지 않는다. 논리 broker 이름은 `kafka` 하나다.
- 설정: `config/module-defaults/messaging.yml`을 support의 `ModuleDefaultsEnvironmentPostProcessor`가
읽는다. 우선순위가 가장 낮아서 `application*.yml`, 환경 변수, 시스템 속성이 항상 이긴다.
app-bootstrap은 이 파일을 모른다.
- broker 주소는 `APP_MESSAGING_KAFKA_BROKERS` 하나(`app.messaging.brokers.kafka.bootstrap-servers`).
`spring.kafka.bootstrap-servers`는 읽지 않는다. 논리 broker 이름은 `kafka` 하나다. Kafka 연결의
TLS·SASL은 platform의 broker profile이 소유한다(`docs/messaging/configuration-reference.md`).
- 발행 경로는 하나다. 옛 `KafkaSender` seam(TLS/SASL 없는 R0 producer)은 outbox를 canonical로
통일하면서 삭제했다(2026-09-28).
- 발행할 event의 contract마다 destination을 선언해야 한다(`app.messaging.destinations.<logical
destination>`). 템플릿의 durable operation event는 `durable-operations`로 간다.
## 추가할 한 줄
@@ -48,8 +53,9 @@ runtimeOnly project(':adapter:outbound:messaging-kafka') // Kafka 발행
| 언제 | 키 |
| --- | --- |
| 항상 | `APP_MESSAGING_KAFKA_BROKERS` (CSV `host:port`). 비어 있으면 기동이 실패한다 |
| canonical integration event를 보낼 때 | `APP_MESSAGING_PRODUCER_ID` (배포와 무관한 논리적 서비스 이름) |
| 항상 | `APP_MESSAGING_PRODUCER_ID` (배포와 무관한 논리적 서비스 이름). 비어 있으면 기동이 실패한다 — 모든 발행이 canonical bridge를 지난다 |
| 끌 때 | `APP_MESSAGING_ENABLED=false` |
`APP_MESSAGING_BROKER`는 기본값이 `kafka`다. 등록된 broker가 Kafka 하나라 바꿀 일이 없다.
destination·broker profile·보안 설정은 `docs/messaging/configuration-reference.md`.
`APP_MESSAGING_BROKER`는 platform이 쓸 broker 선택값이고 기본값이 `kafka`다. 등록된 broker가 Kafka
하나라 바꿀 일이 없다. destination·broker profile·보안 설정은
`docs/messaging/configuration-reference.md`.
@@ -7,9 +7,11 @@ plugins {
//
// runtimeOnly project(':adapter:outbound:messaging-kafka')
//
// That line brings the broker-neutral application bridge (adapter:outbound:messaging), the legacy
// KafkaSender seam in this leaf, the vendored messaging platform with its Kafka transport, and the
// capability's settings (config/module-defaults/messaging.yml). Deleting it removes all of them.
// That line brings the broker-neutral application bridge (adapter:outbound:messaging), the vendored
// messaging platform with its Kafka transport, and the capability's settings
// (config/module-defaults/messaging.yml). Deleting it removes all of them. The leaf has no code of
// its own: it is the selection, not an adapter. Its one test boots the capability the way an
// application gets it.
// Every project shares the group dev.caskeleton, and the vendored transport is also named
// messaging-kafka (:messaging:messaging-kafka). Same group and name is the same module to Gradle,
@@ -24,16 +26,14 @@ base {
}
dependencies {
implementation project(':adapter:outbound:messaging')
implementation 'org.apache.kafka:kafka-clients'
implementation 'org.springframework.boot:spring-boot-autoconfigure'
// The platform publisher behind the canonical IntegrationEventPublishPort bridge. Runtime only:
// this leaf names none of its types; the bridge reaches it through EncodedMessagePublisher.
// Runtime only: this leaf names none of their types. The bridge publishes the application's
// canonical events through the platform's EncodedMessagePublisher, which the Kafka starter
// provides.
runtimeOnly project(':adapter:outbound:messaging')
runtimeOnly project(':messaging:messaging-spring-boot-starter-kafka')
// The activation test boots the whole capability and names the ports it must produce.
testImplementation project(':adapter:outbound:messaging')
testImplementation project(':application-core')
testImplementation project(':messaging:messaging-schema-api')
}
@@ -38,13 +38,13 @@ com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspat
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
commons-logging:commons-logging:1.3.6=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
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
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-commons:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-core:1.16.7=runtimeClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.projectreactor:reactor-core:3.8.7=runtimeClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -63,7 +63,7 @@ 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.kafka:kafka-clients:4.1.2=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.kafka:kafka-clients:4.1.2=runtimeClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-api:2.25.5=runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.logging.log4j:log4j-to-slf4j:2.25.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -86,7 +86,7 @@ org.dom4j:dom4j:2.2.0=spotbugs
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
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
@@ -120,7 +120,7 @@ org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileCl
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.boot:spring-boot-actuator:4.0.8=runtimeClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-autoconfigure:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor
org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -142,12 +142,12 @@ org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRunti
org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:4.0.8=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-jdbc:7.0.9=runtimeClasspath,testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-tx:7.0.9=runtimeClasspath,testRuntimeClasspath
@@ -160,4 +160,4 @@ org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.1.5=runtimeClasspath,testCompileClasspath,testRuntimeClasspath
empty=
empty=compileClasspath
@@ -1,108 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import java.util.Objects;
/**
* One broker endpoint, parsed rather than pattern-matched.
*
* <p>The regular expression it replaces accepted several things that are not addresses. It ran
* against the <em>trimmed</em> value but the untrimmed original was what got stored, so {@code "
* kafka:9092"} passed validation and was then handed to the client with its leading space. {@code
* \\d{1,5}} accepts {@code 0} and {@code 99999}, neither of which is a port. And {@code [^:\\s]+}
* cannot express a bracketed IPv6 literal at all, so {@code [::1]:9092} — the only correct way to
* write an IPv6 endpoint — was rejected while {@code ::1:9092} was accepted and is ambiguous.
*
* @param host the host, without brackets for an IPv6 literal
* @param port the port, between 1 and 65535
* @param ipv6Literal whether the host was written as a bracketed IPv6 literal
*/
public record BrokerAddress(String host, int port, boolean ipv6Literal) {
private static final int MIN_PORT = 1;
private static final int MAX_PORT = 65_535;
/** Validates the parsed components. */
public BrokerAddress {
Objects.requireNonNull(host, "host must not be null");
if (host.isBlank()) {
throw new IllegalArgumentException("broker host must not be blank");
}
if (port < MIN_PORT || port > MAX_PORT) {
throw new IllegalArgumentException("broker port " + port + " is outside 1..65535");
}
}
/**
* Parses one {@code host:port} entry.
*
* @param raw the configured entry, possibly with surrounding whitespace
* @return the canonical address
* @throws IllegalArgumentException naming what is wrong with the entry
*/
public static BrokerAddress parse(String raw) {
if (raw == null || raw.isBlank()) {
throw new IllegalArgumentException("a broker entry must not be blank");
}
String entry = raw.trim();
if (entry.startsWith("[")) {
int closing = entry.indexOf(']');
if (closing < 0 || closing + 1 >= entry.length() || entry.charAt(closing + 1) != ':') {
throw new IllegalArgumentException(
"broker entry '" + entry + "' is a bracketed host without a ':port' after the bracket");
}
String host = entry.substring(1, closing);
if (host.isBlank()) {
throw new IllegalArgumentException("broker entry '" + entry + "' has an empty host");
}
return new BrokerAddress(host, parsePort(entry, entry.substring(closing + 2)), true);
}
int separator = entry.lastIndexOf(':');
if (separator < 0) {
throw new IllegalArgumentException("broker entry '" + entry + "' is not host:port");
}
String host = entry.substring(0, separator);
if (host.isBlank() || host.indexOf(':') >= 0) {
// A bare IPv6 literal reaches here: it contains colons, and which one separates the port is
// not decidable. Brackets are how the ambiguity is resolved, so require them.
throw new IllegalArgumentException(
"broker entry '"
+ entry
+ "' is not host:port; write an IPv6 address in brackets, as [::1]:9092");
}
if (host.chars().anyMatch(Character::isWhitespace)) {
throw new IllegalArgumentException(
"broker entry '" + entry + "' has whitespace inside the host");
}
return new BrokerAddress(host, parsePort(entry, entry.substring(separator + 1)), false);
}
private static int parsePort(String entry, String port) {
if (port.isEmpty() || !port.chars().allMatch(Character::isDigit)) {
throw new IllegalArgumentException(
"broker entry '" + entry + "' does not end in a numeric port");
}
int parsed;
try {
parsed = Integer.parseInt(port);
} catch (NumberFormatException tooLong) {
throw new IllegalArgumentException(
"broker entry '" + entry + "' has a port outside 1..65535", tooLong);
}
if (parsed < MIN_PORT || parsed > MAX_PORT) {
// Reported here rather than in the constructor so the message names the offending entry: an
// operator reading "port 0 is invalid" against a list of nine brokers learns nothing.
throw new IllegalArgumentException(
"broker entry '" + entry + "' has port " + parsed + ", outside 1..65535");
}
return parsed;
}
/**
* The canonical {@code host:port} form, which is what the client is given.
*
* @return the canonical text
*/
public String canonical() {
return ipv6Literal ? "[" + host + "]:" + port : host + ":" + port;
}
}
@@ -1,32 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Layer 1 gating for the Kafka broker template: registers the Kafka {@link MessageBroker} only when
* {@code app.messaging.broker=kafka}. The central {@code MessagingConfig} binds both messaging
* ports onto it.
*
* <p>Needs a project-supplied {@link KafkaSender} bean (the integration seam) and a non-empty
* {@code app.messaging.kafka.brokers}. Adding another broker is a new config like this one — this
* file never changes.
*/
@Configuration
@EnableConfigurationProperties(KafkaAdapterSettings.class)
public class KafkaAdapterConfig {
@Bean
@ConditionalOnProperty(name = "app.messaging.broker", havingValue = "kafka")
public MessageBroker kafkaMessageBroker(KafkaSender sender, KafkaAdapterSettings settings) {
if (settings.brokers().isEmpty()) {
throw new IllegalStateException(
"app.messaging.broker=kafka requires a non-empty app.messaging.kafka.brokers "
+ "(CSV of host:port)");
}
return new KafkaMessageBroker(sender);
}
}
@@ -1,48 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Kafka broker tuning bound from {@code app.messaging.kafka.*}.
*
* <p>Each entry is parsed into a {@link BrokerAddress} and stored in its canonical form. The
* previous binding validated the trimmed value with a regular expression and then stored the
* untrimmed original, so a configured {@code " kafka:9092"} passed the check and reached the client
* with its leading space; the same expression accepted port {@code 0} and port {@code 99999}, and
* could not express a bracketed IPv6 literal.
*
* <p>The "Kafka selected implies brokers required" cross-field rule stays in {@code
* KafkaAdapterConfig}, so an empty list is still valid at bind time.
*
* @param brokers CSV of {@code host:port} broker endpoints, canonicalised
*/
@ConfigurationProperties(prefix = "app.messaging.kafka")
public record KafkaAdapterSettings(List<String> brokers) {
/** Parses and canonicalises every configured entry. */
public KafkaAdapterSettings {
List<String> configured = (brokers == null) ? List.of() : List.copyOf(brokers);
brokers =
configured.stream()
.map(
entry -> {
try {
return BrokerAddress.parse(entry).canonical();
} catch (IllegalArgumentException invalid) {
throw new IllegalArgumentException(
"APP_MESSAGING_KAFKA_BROKERS " + invalid.getMessage(), invalid);
}
})
.toList();
}
/**
* The parsed addresses, for callers that need the components rather than the text.
*
* @return one address per configured entry
*/
public List<BrokerAddress> addresses() {
return brokers.stream().map(BrokerAddress::parse).toList();
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
/**
* Kafka contribution of the {@link MessageBroker} SPI (brokerId {@code "kafka"}). Delegates the raw
* send to the project-supplied {@link KafkaSender} seam; the fail-open (general) and fail-closed
* (outbox) policies are applied by the binding decorators in the messaging package, not here — so
* this class carries no policy and no Kafka SDK.
*/
public class KafkaMessageBroker implements MessageBroker {
private static final String BROKER_ID = "kafka";
private final KafkaSender sender;
public KafkaMessageBroker(KafkaSender sender) {
this.sender = sender;
}
@Override
public String brokerId() {
return BROKER_ID;
}
@Override
public void send(OutboundMessage message) throws Exception {
sender.send(message);
}
}
@@ -1,19 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
/**
* Integration seam the forking project implements to bind the Kafka template to a real producer.
* The skeleton carries no Kafka SDK dependency — it is added by the project that enables Kafka. A
* send failure may throw; the binding decorator applies the failure policy.
*/
@FunctionalInterface
public interface KafkaSender {
/**
* Sends a message to the broker. May throw on any transport/broker failure.
*
* @throws Exception on any send failure (caught and handled fail-open by the publisher)
*/
void send(OutboundMessage message) throws Exception;
}
@@ -1,120 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The adapter-owned broker bridge behind {@link KafkaSender} (MSG-INT-003).
*
* <p>{@code KafkaSender} is documented as an integration seam for a forking project, and the
* skeleton supplied no implementation of it — only a test fake. So selecting {@code
* app.messaging.broker=kafka} against a healthy broker failed startup on a missing bean, and the
* messaging capability had no way to reach a broker in any deployment. A seam with no production
* implementation anywhere is indistinguishable from an unimplemented feature.
*
* <p>It stays a seam and is owned by the outbound messaging adapter. The bean backs off entirely to
* anything a forking project defines, and it is registered only when Kafka is the selected broker —
* so a deployment with messaging off, or on a different broker, carries no producer, no connection
* and no background sender thread.
*
* <p>{@code kafka-clients} rather than {@code spring-kafka}: the seam takes one already-serialized
* message and returns nothing, so a listener container, a converter stack and a template would all
* be unused weight on the classpath of every deployment.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "app.messaging.broker", havingValue = "kafka")
public class KafkaSenderAutoConfiguration {
/**
* The producer, configured so a send that returns has actually been accepted.
*
* <p>{@code acks=all} with idempotence, because the seam's contract is that a normal return means
* the broker took the message. A producer with {@code acks=1} returns before replication and a
* non-idempotent one can duplicate on internal retry; either would make a successful return mean
* less than the callers of this seam assume.
*
* <p>Named and conditioned by name, not by type. The messaging platform's own {@code
* KafkaMessagingAutoConfiguration} declares a {@code Producer} bean too — a {@code
* Producer<byte[], byte[]>} for its transport, against a different switch — and the two shipped
* together the moment the platform facade joined the runtime classpath. Sharing the method name
* {@code messagingKafkaProducer} made the context refuse to start with a {@code
* BeanDefinitionOverrideException}, and a type-scoped {@code @ConditionalOnMissingBean} would
* have been worse: whichever configuration lost the race would leave its own stack without a
* producer while the other stack's, with incompatible serializers, sat in its place.
*
* @param settings the broker addresses, already validated as non-empty when Kafka is selected
* @return the producer, closed on context shutdown
*/
@Bean(name = "kafkaSeamProducer", destroyMethod = "close")
@ConditionalOnMissingBean(name = "kafkaSeamProducer")
public Producer<String, String> kafkaSeamProducer(KafkaAdapterSettings settings) {
Map<String, Object> config = new HashMap<>();
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, String.join(",", settings.brokers()));
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.ACKS_CONFIG, "all");
config.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
// Bounded, so a broker that stops answering surfaces as a failed send rather than as a caller
// blocked for the default two minutes inside a dispatch worker.
//
// All three are stated, not two of three. Kafka enforces
// delivery.timeout.ms >= linger.ms + request.timeout.ms and refuses to construct the producer
// otherwise; setting only the delivery timeout left request.timeout.ms at its default and the
// sum came out exactly equal, which the check rejects.
config.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, 10_000);
config.put(ProducerConfig.LINGER_MS_CONFIG, 0);
config.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 15_000);
config.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, 30_000);
return new KafkaProducer<>(config);
}
/**
* The seam itself.
*
* <p>Waits for the broker's acknowledgement rather than returning on enqueue. {@code
* Producer.send} is asynchronous and returns a future the moment the record is buffered, so a
* fire-and-forget implementation would satisfy the seam's signature while reporting success for a
* message the broker never saw — and the publisher above it applies a failure policy it would
* then never be given the chance to apply.
*
* @param producer the configured producer
* @return the sender
*/
@Bean
@ConditionalOnMissingBean(KafkaSender.class)
public KafkaSender kafkaSender(
@Qualifier("kafkaSeamProducer") Producer<String, String> producer) {
Duration ackTimeout = Duration.ofSeconds(30);
return message -> {
try {
producer
.send(
new ProducerRecord<>(
message.topic(),
// An empty key means "no key" to Kafka, which is round-robin partitioning. The
// seam models an absent key as the empty string, and passing that through as a
// literal key would put every unkeyed message on one partition.
message.key().isEmpty() ? null : message.key(),
message.payload()))
.get(ackTimeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException interrupted) {
// Future.get cleared the flag when it threw, and the callers above catch Exception. Without
// restoring it, a relay being shut down kept waiting out every remaining row's timeout.
Thread.currentThread().interrupt();
throw interrupted;
}
};
}
}
@@ -1,21 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Import;
/**
* Build-time Kafka capability for the legacy R0 messaging seam.
*
* <p>The broker-neutral messaging bridge no longer imports Kafka classes. An application that still
* needs the R0 Kafka seam must deliberately add this leaf; only then can the Kafka producer/client
* enter its runtime graph. Present means on; {@code app.messaging.enabled=false} turns it off.
*/
@AutoConfiguration
@ConditionalOnProperty(
prefix = "app.messaging",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
@Import({KafkaSenderAutoConfiguration.class, KafkaAdapterConfig.class})
public class LegacyKafkaMessagingRootAutoConfiguration {}
@@ -1 +0,0 @@
dev.caskeleton.adapter.outbound.messaging.kafka.LegacyKafkaMessagingRootAutoConfiguration
@@ -7,10 +7,11 @@ app:
messaging:
# true | false — 모듈이 있으면 켜진다. false 로만 끈다.
enabled: ${APP_MESSAGING_ENABLED:true}
# 이 모듈을 고른 서비스는 Kafka 를 쓴다. 등록된 broker 는 kafka 하나다.
# messaging platform 이 쓸 broker. 등록된 broker 는 kafka 하나다.
broker: ${APP_MESSAGING_BROKER:kafka}
# canonical IntegrationEventPublishPort bridge 의 producer id. 비어 있으면 bridge 가 없다.
# host/pod/process 이름에서 추측하지 않는다.
# canonical IntegrationEventPublishPort bridge 의 producer id. 모든 발행(outbox relay 포함)이 이
# bridge 를 지나므로 켜진 상태에서 비어 있으면 기동이 실패한다. host/pod/process 이름에서 추측하지
# 않는다.
producer-id: ${APP_MESSAGING_PRODUCER_ID:}
# messaging platform 의 Kafka transport 가 연결하는 broker. 논리 이름은 kafka 하나다.
# 비어 있으면 기동이 실패한다(app.messaging.brokers.kafka.bootstrap-servers).
@@ -18,9 +19,6 @@ app:
kafka:
type: kafka
bootstrap-servers: ${APP_MESSAGING_KAFKA_BROKERS:}
kafka:
# CSV host:port. 같은 주소를 legacy KafkaSender seam 에도 준다.
brokers: ${APP_MESSAGING_KAFKA_BROKERS:}
# /actuator/info 에 싣는 이 모듈의 상태(management.info.env). compose smoke 가 lane 이 실제로 켠
# capability 를 이 값으로 확인한다. 위 스위치를 해석한 값이고, 기본값은 messaging root
@@ -1,120 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
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 java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* What counts as a broker endpoint.
*
* <p>The regular expression that decided this ran against the trimmed value and then stored the
* untrimmed original, accepted port 0 and port 99999, and could not express a bracketed IPv6
* literal at all — so the only correct way to write an IPv6 endpoint was rejected while an
* ambiguous one was accepted.
*/
class BrokerAddressTest {
@Test
@DisplayName("an ordinary endpoint parses and canonicalises")
void anOrdinaryEndpointParses() {
BrokerAddress address = BrokerAddress.parse("kafka-1.internal:9092");
assertThat(address.host()).isEqualTo("kafka-1.internal");
assertThat(address.port()).isEqualTo(9092);
assertThat(address.canonical()).isEqualTo("kafka-1.internal:9092");
}
@Test
@DisplayName("surrounding whitespace is removed rather than validated away and kept")
void surroundingWhitespaceIsRemoved() {
assertThat(new KafkaAdapterSettings(List.of(" kafka:9092 ")).brokers())
.as("the old binding validated the trimmed value and stored the untrimmed one")
.containsExactly("kafka:9092");
}
@Test
@DisplayName("whitespace inside the host is refused")
void whitespaceInsideTheHostIsRefused() {
assertThatThrownBy(() -> BrokerAddress.parse("kaf ka:9092"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("whitespace");
}
@Test
@DisplayName("the port range is 1 to 65535")
void thePortRangeIsOneToSixtyFiveThousand() {
assertThatCode(() -> BrokerAddress.parse("kafka:1")).doesNotThrowAnyException();
assertThatCode(() -> BrokerAddress.parse("kafka:65535")).doesNotThrowAnyException();
assertThatThrownBy(() -> BrokerAddress.parse("kafka:0"))
.as("port 0 asks the operating system to choose, which a client cannot connect to")
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> BrokerAddress.parse("kafka:65536"))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> BrokerAddress.parse("kafka:99999"))
.as("the five-digit pattern accepted this")
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("a bracketed IPv6 literal is accepted and stays bracketed")
void aBracketedIpv6LiteralIsAccepted() {
BrokerAddress address = BrokerAddress.parse("[2001:db8::1]:9092");
assertThat(address.host()).isEqualTo("2001:db8::1");
assertThat(address.port()).isEqualTo(9092);
assertThat(address.ipv6Literal()).isTrue();
assertThat(address.canonical()).isEqualTo("[2001:db8::1]:9092");
}
@Test
@DisplayName("a bare IPv6 literal is refused because it is ambiguous")
void aBareIpv6LiteralIsRefused() {
assertThatThrownBy(() -> BrokerAddress.parse("2001:db8::1:9092"))
.as("which colon separates the port is not decidable, so brackets are required")
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("[::1]:9092");
}
@Test
@DisplayName("a bracketed host with no port is refused")
void aBracketedHostWithNoPortIsRefused() {
assertThatThrownBy(() -> BrokerAddress.parse("[2001:db8::1]"))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> BrokerAddress.parse("[2001:db8::1]9092"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("an entry with no port at all is refused")
void anEntryWithNoPortIsRefused() {
assertThatThrownBy(() -> BrokerAddress.parse("kafka"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("host:port");
assertThatThrownBy(() -> BrokerAddress.parse("kafka:"))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> BrokerAddress.parse("kafka:http"))
.isInstanceOf(IllegalArgumentException.class);
assertThatThrownBy(() -> BrokerAddress.parse(":9092"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("the settings binding reports which entry is wrong")
void theSettingsBindingReportsWhichEntryIsWrong() {
assertThatThrownBy(() -> new KafkaAdapterSettings(List.of("kafka-1:9092", "kafka-2:0")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("APP_MESSAGING_KAFKA_BROKERS")
.hasMessageContaining("kafka-2:0");
}
@Test
@DisplayName("an absent broker list is empty, not a failure")
void anAbsentBrokerListIsEmpty() {
assertThat(new KafkaAdapterSettings(null).brokers()).isEmpty();
}
}
@@ -1,41 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
class KafkaAdapterSettingsTest {
@Test
void emptyOrNullBrokersIsTolerated() {
// bound globally via @ConfigurationPropertiesScan even when Kafka is not the active
// broker — an empty list must bind cleanly (the "required" guard lives in the config).
assertThat(new KafkaAdapterSettings((List<String>) null).brokers()).isEmpty();
assertThat(new KafkaAdapterSettings(List.of()).brokers()).isEmpty();
}
@Test
void rejectsABrokerThatIsNotHostPort() {
assertThatThrownBy(() -> new KafkaAdapterSettings(List.of("not-a-broker")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("host:port");
}
@Test
void acceptsCsvOfHostPortBrokers() {
KafkaAdapterSettings settings =
new KafkaAdapterSettings(List.of("broker-1:9092", "broker-2:9092"));
assertThat(settings.brokers()).containsExactly("broker-1:9092", "broker-2:9092");
}
@Test
void brokersListIsDefensivelyCopied() {
List<String> mutable = new ArrayList<>(List.of("broker-1:9092"));
KafkaAdapterSettings settings = new KafkaAdapterSettings(mutable);
mutable.add("broker-2:9092");
assertThat(settings.brokers()).containsExactly("broker-1:9092");
}
}
@@ -1,17 +1,14 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessagePublisher;
import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -28,30 +25,38 @@ import org.springframework.context.annotation.Configuration;
class KafkaCapabilityActivationTest {
@Test
void presentModuleIsOnAndPublishesThroughKafka() {
// given — only the broker address; everything else is the module's own default
void presentModulePublishesEveryOutboxRowThroughTheCanonicalPlatformBridge() {
// given — the broker address and the producer identity; everything else is the module's default
try (ConfigurableApplicationContext context =
start("--APP_MESSAGING_KAFKA_BROKERS=localhost:1", "--APP_MESSAGING_PRODUCER_ID=orders")) {
// then
assertThat(context.getBean(MessageBroker.class)).isInstanceOf(KafkaMessageBroker.class);
assertThat(context.getBean(MessagePublisher.class))
.isInstanceOf(OutboundMessagePublisher.class);
assertThat(context.getBean(OutboxMessagePublishPort.class))
.isInstanceOf(OutboxMessagePublishAdapter.class);
assertThat(context.getBeanNamesForType(EncodedMessagePublisher.class)).hasSize(1);
assertThat(context.getBeanNamesForType(IntegrationEventPublishPort.class)).hasSize(1);
assertThat(
List.of(
context.getBean(OutboxMessagePublishPort.class).getClass(),
context.getBeanNamesForType(EncodedMessagePublisher.class).length,
context.getBeanNamesForType(IntegrationEventPublishPort.class).length))
.containsExactly(OutboxMessagePublishAdapter.class, 1, 1);
}
}
@Test
void presentModuleWithoutABrokerAddressRefusesToStart() {
assertThatThrownBy(() -> start().close())
.satisfiesAnyOf(
failure ->
assertThat(failure)
.hasStackTraceContaining("app.messaging.brokers.kafka.bootstrap-servers"),
failure -> assertThat(failure).hasStackTraceContaining("app.messaging.kafka.brokers"));
// when
Throwable thrown = catchThrowable(() -> start("--APP_MESSAGING_PRODUCER_ID=orders").close());
// then
assertThat(thrown).hasStackTraceContaining("app.messaging.brokers.kafka.bootstrap-servers");
}
@Test
void presentModuleWithoutAProducerIdRefusesToStartBecauseNothingCouldPublish() {
// when
Throwable thrown =
catchThrowable(() -> start("--APP_MESSAGING_KAFKA_BROKERS=localhost:1").close());
// then
assertThat(thrown).hasStackTraceContaining("no IntegrationEventPublishPort exists");
}
@Test
@@ -68,7 +73,6 @@ class KafkaCapabilityActivationTest {
|| name.startsWith("dev.caskeleton.adapter.outbound.messaging.")
|| name.startsWith("org.apache.kafka.")))
.isEmpty();
assertThat(context.getBeanNamesForType(DisabledMessagePublisher.class)).isEmpty();
}
}
@@ -1,18 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Import;
class KafkaSenderAutoConfigurationOwnershipTest {
@Test
void kafkaCapabilityRootOwnsTheProductionKafkaSenderInsideTheAdapter() {
Import imports = LegacyKafkaMessagingRootAutoConfiguration.class.getAnnotation(Import.class);
assertThat(imports).isNotNull();
assertThat(Arrays.asList(imports.value()))
.contains(KafkaSenderAutoConfiguration.class, KafkaAdapterConfig.class);
}
}
@@ -1,42 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
import org.apache.kafka.clients.producer.MockProducer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
class KafkaSenderInterruptionTest {
@AfterEach
void clearInterrupt() {
Thread.interrupted();
}
/**
* An interrupted wait for the broker's acknowledgement leaves the thread interrupted.
*
* <p>{@code Future.get} clears the flag when it throws, and the callers above this seam catch
* {@code Exception}. So the interrupt that was meant to stop a relay during shutdown vanished,
* and the relay spent up to thirty seconds on every remaining row.
*/
@Test
void anInterruptedAcknowledgementWaitRethrowsWithTheInterruptFlagRestored() {
// given
KafkaSender sender =
new KafkaSenderAutoConfiguration()
.kafkaSender(
new MockProducer<>(false, null, new StringSerializer(), new StringSerializer()));
Thread.currentThread().interrupt();
// when
Throwable thrown = catchThrowable(() -> sender.send(new OutboundMessage("topic", "k", "v")));
// then
assertThat(new Object[] {thrown.getClass(), Thread.currentThread().isInterrupted()})
.containsExactly(InterruptedException.class, true);
}
}
@@ -1,103 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.kafka;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.core.annotation.AnnotatedElementUtils;
/**
* This leaf's auto-configurations are registered, not merely annotated.
*
* <p>Spring Boot needs two independent things before an auto-configuration runs: the annotation on
* the class, and a line naming it in {@code META-INF/spring/...AutoConfiguration.imports}. Tests
* that build a context with {@code AutoConfigurations.of(...)} supply the second one themselves, so
* they stay green for a capability that is present in no running application — which is exactly how
* several capabilities in this repository came to be assembled by nothing.
*
* <p>So this reads the registration file the jar actually ships and asserts both directions: every
* class this leaf means to register is named in it, and every name in it resolves to a class that
* carries {@code @AutoConfiguration}. A rename, a move or a deleted line fails here rather than in
* a deployment that starts and quietly does less than it says.
*/
class LegacyKafkaAutoConfigurationRegistrationTest {
private static final String IMPORTS_RESOURCE =
"META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports";
/** The auto-configurations this leaf publishes. */
private static final List<String> PUBLISHED_ROOTS =
List.of(
"dev.caskeleton.adapter.outbound.messaging.kafka.LegacyKafkaMessagingRootAutoConfiguration");
@Test
@DisplayName("the shipped registration file names every root this leaf publishes")
void theShippedRegistrationFileNamesEveryRoot() {
assertThat(registeredNames())
.as("the registration lines this leaf's own jar ships")
.containsAll(PUBLISHED_ROOTS);
}
@Test
@DisplayName("every registered name resolves to a real Boot auto-configuration")
void everyRegisteredNameResolvesToAnAutoConfiguration() {
for (String name : registeredNames()) {
Class<?> registered;
try {
registered =
Class.forName(
name, false, LegacyKafkaAutoConfigurationRegistrationTest.class.getClassLoader());
} catch (ClassNotFoundException missing) {
throw new AssertionError(
IMPORTS_RESOURCE + " registers " + name + ", which does not exist", missing);
}
assertThat(AnnotatedElementUtils.hasAnnotation(registered, AutoConfiguration.class))
.as("%s is registered but is not annotated @AutoConfiguration", name)
.isTrue();
}
}
/**
* The registration lines this leaf's own resource declares.
*
* <p>Read from this leaf's source tree rather than from the classpath. {@code
* ClassLoader#getResources} returns every registration file on the test runtime classpath —
* Spring Boot's, springdoc's, and every dependency leaf's — so asserting over that set tests
* other people's modules and fails on their conditional classes. The file below is the one this
* leaf packages, which is the thing this contract is about.
*/
private static List<String> registeredNames() {
Path resource = leafRoot().resolve("src/main/resources/" + IMPORTS_RESOURCE);
assertThat(Files.isRegularFile(resource)).as("%s", resource).isTrue();
List<String> names;
try {
names =
Files.readAllLines(resource, StandardCharsets.UTF_8).stream()
.map(String::strip)
.filter(line -> !line.isEmpty() && !line.startsWith("#"))
.toList();
} catch (IOException failure) {
throw new UncheckedIOException("cannot read " + resource, failure);
}
assertThat(names).as("%s registers nothing", resource).isNotEmpty();
return names;
}
/** The nearest directory above the test's working directory that ships a registration file. */
private static Path leafRoot() {
for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) {
if (Files.isRegularFile(path.resolve("src/main/resources/" + IMPORTS_RESOURCE))) {
return path;
}
}
throw new IllegalStateException(
"no leaf shipping " + IMPORTS_RESOURCE + " found above " + Path.of("").toAbsolutePath());
}
}
+14 -13
View File
@@ -26,23 +26,24 @@ Package root: `dev.caskeleton.adapter.outbound.messaging`.
- The canonical platform bridge may depend only on `messaging-core-api` and
`messaging-schema-api`; do not import `messaging-runtime-core`, transport SPI implementations, or
broker SDK types under `platformbridge/`.
- `KafkaSender` / `MessageBroker` are transitional legacy R0 seams for `OutboxEvent` and realtime
compatibility only. Do not route new canonical integration-event publication through them.
- There is one publication path: `OutboxMessagePublishAdapter` → `IntegrationEventPublishPort` →
the platform bridge. The legacy `KafkaSender` / `MessageBroker` R0 seam and the fail-open
`MessagePublisher` were removed with the canonical outbox (2026-09-28); do not reintroduce a
second path.
- Canonical producer identity is explicit `app.messaging.producer-id`; never derive it from
`spring.application.name`, host, pod, or process identity.
- The template ships no `IntegrationEventEncoderPort` implementation. The R1 contract compiler,
binding compiler, JSON Schema envelope encoder and capability card registry (`contract/`,
`destination/`, `envelope/`, `config/`) and the durable realtime fan-out adapter (`realtime/`)
were removed on 2026-09-25 (see `docs/capability-status.md`); an adopter that turns on canonical
transport provides its own encoder.
`spring.application.name`, host, pod, or process identity. With the module on and no bridge,
startup is refused — the relay would have nothing to publish through.
- The template's `IntegrationEventEncoderPort` (`JsonIntegrationEventEncoder`) lives in
`adapter:outbound:support`, not here: a use case encodes before it appends, in compositions that
may not carry this module. The R1 contract/binding compilers and JSON Schema envelope encoder were
removed on 2026-09-25 (see `docs/capability-status.md`).
- No JSON Schema engine (NetworkNT) here. The evidence manifest schema check moved to build-tools
(`VerifyMessagingEvidenceTask`).
- Do not hide use-case sequencing or business routing policy in broker adapters.
- `OutboxMessagePublishAdapter` is mapping/send-only and emits no dependency log. The confirmed
FAILED/DEAD transition owns the one canonical ERROR; only the general fail-open publisher keeps
`FailOpenDependencyLogger`.
- `OutboxMessagePublishAdapter` is delegate-only and emits no dependency log. The confirmed
FAILED/DEAD transition owns the one canonical ERROR.
## Tests
Use unit/contract tests with fake broker senders. No real network or broker is used in focused tests;
settings records receive binding/validation tests when configuration changes.
Use unit/contract tests with a fake canonical publisher. No real network or broker is used in
focused tests; settings records receive binding/validation tests when configuration changes.
+38 -79
View File
@@ -1,9 +1,8 @@
# adapter:outbound:messaging — 설계 결정 참조
메시징(broker publish + outbox) 아웃바운드 어댑터 모듈. 패키지 루트:
`dev.caskeleton.adapter.outbound.messaging`. `:adapter:outbound:support` 에 의존해 공유
correlation / fail-open 의존성 로깅을 일반 publisher에서 재사용한다. outbox relay 실패는 이
모듈이 별도의 typed report adapter로 구조화한다.
메시징(broker publish + outbox relay 발행) 아웃바운드 어댑터 모듈. 패키지 루트:
`dev.caskeleton.adapter.outbound.messaging`. outbox relay 실패는 이 모듈이 별도의 typed report
adapter로 구조화한다.
허용/금지 의존 정책은 `src/config/architecture/modules.json`과 이 모듈의
[CLAUDE.md](CLAUDE.md)가 소유한다. 이 문서는 코드 주석에서 덜어낸 **설계 결정의 근거**를 모아둔
@@ -11,110 +10,70 @@ correlation / fail-open 의존성 로깅을 일반 publisher에서 재사용한
## 모듈 개요
application-core의 legacy 포트(`MessagePublisher` / `OutboxMessagePublishPort`)와 canonical
`IntegrationEventPublishPort` 뒤에 두는 **선택형** 연동 어댑터다. 서비스는 이 모듈을 직접 고르지 않고
application-core의 `OutboxMessagePublishPort`와 canonical `IntegrationEventPublishPort` 뒤에 두는
**선택형** 연동 어댑터다. 서비스는 이 모듈을 직접 고르지 않고
`runtimeOnly project(':adapter:outbound:messaging-kafka')` 한 줄로 받는다(추가할 한 줄·env 키는
[messaging-kafka README](../messaging-kafka/README.md)). 모듈이 있으면 켜지고
`app.messaging.enabled=false`로만 끈다. broker가 없을 때의 legacy 바인딩은 `Disabled*` 구현으로
fail-fast 한다(Layer 3).
`app.messaging.enabled=false`로만 끈다.
canonical path는 `platformbridge/PlatformIntegrationEventPublishAdapter`가
`EncodedMessagePublisher`에 위임한다. 이 path는 broker SDK나 transport SPI를 직접 보지 않는다.
`KafkaSender`/`MessageBroker`는 metadata가 부족한 legacy `OutboxEvent`/realtime 경로의 transitional
R0 seam으로만 남아 있고, legacy storage/relay cutover와 함께 제거한다.
발행 경로는 하나다.
## Legacy 두 포트와 canonical platform bridge
`OutboxMessagePublishPort → OutboxMessagePublishAdapter → IntegrationEventPublishPort →
PlatformIntegrationEventPublishAdapter → EncodedMessagePublisher`
`MessagingConfig`는 legacy 두 messaging 포트를 단일 활성 `MessageBroker` 위에 조립한다. 이 경로는
기존 `OutboxEvent`/realtime compatibility를 위해 남아 있다.
bridge는 broker SDK나 transport SPI를 직접 보지 않는다. legacy `KafkaSender`/`MessageBroker` R0
seam과 그 위의 `MessagePublisher`·`OutboxEnvelopeJson`은 outbox를 canonical 하나로 통일하면서
삭제했다(2026-09-28, 소유자 결정 7).
canonical `IntegrationEventPublishPort`는 별도 경로다.
## canonical platform bridge
`IntegrationEventPublishPort → PlatformIntegrationEventPublishAdapter → EncodedMessagePublisher`
`IntegrationEventPublishPort`는 `app.messaging.producer-id`가 명시되고 platform publisher bean이
있을 때만 생성된다. exact `ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙
publish pipeline을 탄다. producer id는 host/pod/process 이름에서 추측하지 않는다.
`app.messaging.producer-id`가 명시되고 platform publisher bean이 있을 때만 생성된다. exact
`ValidatedIntegrationEvent.envelopeBytes()`를 보존하고 platform의 중앙 publish pipeline을 탄다.
MSG-015 transport-only 단계에서는 legacy relay authority도 이 bridge를 사용할 수 있다.
`OutboxMessagePublishAdapter`가 claim subtype으로 경로를 분리해서 legacy `OutboxEvent`는 기존
`MessageBroker`, `CanonicalClaimedOutboxEvent`는 `IntegrationEventPublishPort`만 호출한다. 한 row가 두
transport로 fallback/dual-publish되지 않는다. mixed-row 기간에는 old backlog를 보존하기 위해 legacy
broker requirement도 유지한다.
## broker 선택 검증
`app.messaging.broker` 가 설정됐는데 `MessageBroker` 빈이 없으면 startup 을 명시적 메시지로
실패시킨다(조용한 no-op 아님). settings 와 활성 빈의 `brokerId()` 불일치도 startup 실패다.
`OutboxMessagePublishAdapter`는 claim된 row의 validated event를 그대로 bridge에 넘기고 platform의
네 가지 결과(CONFIRMED·AMBIGUOUS·REJECTED_BEFORE_SEND·REJECTED_AFTER_BROKER)를 relay에 돌려준다.
다시 직렬화하지 않는다.
## outbox 발행 포트에는 대역이 없다
`OutboxMessagePublishPort`의 대역(항상 던지는 publisher)은 두지 않는다. 대역도 bean이므로 relay
스케줄러의 조건을 채우고, relay는 모든 PENDING 행을 그 대역에 실패시켜 DEAD로 소진한다. 그래서
모듈이 있고 켜져 있는데 broker가 비어 있고 canonical transport도 없으면 startup을 거부한다.
`DisabledMessagePublisher`(일반 발행기의 fail-fast 대역)는 남아 있다 — relay가 쓰지 않는다.
모듈이 있고 켜져 있는데 `IntegrationEventPublishPort`가 없으면(producer id가 비었거나 platform
transport가 없으면) startup을 거부한다.
## OutboxEnvelopeJson — 손수 짠 JSON
이 모듈은 `jackson-databind` 를 classpath 에 두지 않아(스켈레톤을 가볍게 유지) outbox envelope
직렬화는 의존성 없는 손수 짠 JSON 이다.
## MessagePublisher vs OutboxMessagePublishPort
`MessagePublisher` 는 fail-open 어댑터-로컬 발행기로, 발행 실패를 correlationId 와 함께
로깅하고 삼켜(→ `:adapter:outbound:support` 의 `FailOpenDependencyLogger`) outbox/retry 로
위임하므로 core 5xx 가 되지 않는다. 내구성 있는 전달이 필요하면 `OutboxMessagePublishPort` 를
쓴다. `OutboxMessagePublishAdapter`는 envelope mapping + broker send만 수행하며 runtime 예외를
그대로 전파하고 checked 예외는 cause를 보존해 감싼다. 성공 DEBUG나 실패 WARN을 남기지 않는다.
반환 타입을 void 로 둬 broker SDK 타입이 어댑터 밖으로 새지 않는다(B7).
## Legacy R0 characterization
현재 `KafkaSender.send(...)`와 `MessageBroker.send(...)`의 정상 void 반환은 호출이 예외 없이
끝났다는 뜻일 뿐 broker acknowledgement 증거가 아니다. relay는 이 정상 반환 뒤 legacy
`PUBLISHED`를 기록한다. sender 예외는 fail-closed outbox 경로에서 전파되어 relay의
`FAILED/DEAD` 전이를 유발한다.
broker 설정이 blank면 `MessagePublisher`는 `DisabledMessagePublisher`에 바인딩되고, canonical
transport도 없으면 startup이 실패한다. broker를 선택했지만 project-supplied sender가 없거나 선택
ID와 활성 `MessageBroker.brokerId()`가 다르면 startup이 실패한다.
## 중복 가능 구간
publisher 정상 반환 뒤 DB mark가 실패하면 row는 `IN_FLIGHT`에 남아 timeout reclaim 후 같은
event가 다시 publish될 수 있다. 현재 consumer/inbox가 없으므로 이 duplicate 가능 구간을
중복 안전 전달로 표현하지 않는다. 또한 legacy FIFO gate는 `occurred_at`의 strict less-than 비교만
사용하므로 동일 aggregate의 timestamp 동률 row는 서로를 gate하지 않는다.
event가 다시 publish될 수 있다. 같은 event id로 다시 나가므로 consumer는 event id로 중복을 걸러야
한다. 같은 aggregate의 row는 `(aggregate_sequence, event_index)` 순서로 하나씩 풀린다.
## OutboxRelayFailureReport 구조화 ERROR
`MessagingConfig`는 broker 활성 여부와 무관하게 정확히 하나의
`Slf4jOutboxRelayFailureReportAdapter`를 등록한다. broker 설정이 blank면 안전한
`dependency_name=disabled`를 쓴다. 이 adapter는 confirmed FAILED/DEAD report 하나를 SLF4J 2 fluent
`MessagingConfig`는 정확히 하나의 `Slf4jOutboxRelayFailureReportAdapter`를 등록한다.
`dependency_name`은 platform이 쓰는 broker 선택값(`app.messaging.broker`, 기본 `kafka`)이고, 비어
있으면 `messaging-platform`이다. 이 adapter는 confirmed FAILED/DEAD report 하나를 SLF4J 2 fluent
ERROR 하나로 렌더링한다.
공통 field는 `error.code`, `error.category`, `dependency_name`,
`dependency_type=messaging`, `outcome`, `event_id`, `event_type`, `aggregate_id`,
`correlation_id`, `attempt_count`, `runbook_link`다. retry report만 `next_attempt_at`을 추가한다.
payload/idempotency key/envelope/exception-derived field는 받거나 렌더링하지 않고 cause만 throwable로
붙인다. logging 내부 `RuntimeException`은 adapter와 use case 양쪽에서 방어하므로 persisted
FAILED/DEAD outcome을 바꾸지 않는다.
payload/envelope/exception-derived field는 받거나 렌더링하지 않는다. logging 내부
`RuntimeException`은 adapter와 use case 양쪽에서 방어하므로 persisted FAILED/DEAD outcome을 바꾸지
않는다.
## 제거된 R1 encoder 체인 (2026-09-25)
## encoder는 이 모듈에 없다
`contract`·`destination`·`config`(로컬 contract/binding 컴파일러, capability card registry),
`envelope`(결정적 JSON Schema envelope encoder, `LocalJsonSchemaRegistry`, pin한 Draft 2020-12
meta-schema), `realtime`(durable fan-out adapter)은 조립하는 곳이 없어 삭제했다. 복구 경로는
`docs/capability-status.md`의 제거 표에 있다. 그 결과 NetworkNT는 이 leaf의 production 의존성이
아니다.
`IntegrationEventEncoderPort`는 adopter 확장 지점으로 남는다. 템플릿은 구현체를 주지 않으므로
`ca-skeleton.outbox.canonical-transport-enabled=true`를 켜는 adopter가 encoder bean을 직접 제공한다.
템플릿의 `IntegrationEventEncoderPort` 구현(`JsonIntegrationEventEncoder`)은
`adapter:outbound:support`에 있다. use case가 append 전에 encode하므로 outbox를 쓰는 모든 조립에
있어야 하고, 이 모듈은 발행 쪽에만 있다. 옛 R1 encoder 체인(`contract`·`destination`·`config`·
`envelope`·`realtime`)은 2026-09-25에 삭제됐고 복구 경로는 `docs/capability-status.md` 제거 표에
있다.
공통 build evidence manifest 검증은 build-tools로 옮겼다. 루트 `verifyMessagingContracts`
(`VerifyMessagingEvidenceTask`)가 application-core·shared-contract 두 qualification 레인 결과로
`build/messaging-evidence/contracts-schema/manifest.json`을 쓰고, 쓴 바이트를 바로 common schema로
검증한다(common schema 자체도 Draft 2020-12 meta-schema 검증을 먼저 통과해야 한다). 이 leaf는 그
검증에 관여하지 않는다.
검증한다. 이 leaf는 그 검증에 관여하지 않는다.
canonical path는 platform `PublishResult`의 confirmation/transmission evidence를 application
`OutboxPublishOutcome`으로 명시적으로 변환한다. production legacy relay가 아직 `OutboxEvent`를 읽기
때문에 R2 durable outbox storage/relay cutover는 남아 있고, `KafkaSender`/legacy broker selection은 그
R0 compatibility path에서만 authority를 유지한다.
`OutboxPublishOutcome`으로 명시적으로 변환한다.
@@ -14,11 +14,6 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-json'
implementation 'org.slf4j:slf4j-api'
// Test-only: the Kafka broker template, for the broker-selection cases. Without the platform
// starter it pulls at runtime — this leaf's tests use a same-named stand-in for the platform root.
testImplementation(project(':adapter:outbound:messaging-kafka')) {
exclude group: 'dev.caskeleton', module: 'messaging-spring-boot-starter-kafka'
}
// Test-only: MessagingEvidenceSchemaValidatorTest holds the common evidence schema to Draft 2020-12.
testImplementation libs.json.schema.validator
}
@@ -1,7 +1,6 @@
# 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.
at.yawk.lz4:lz4-java:1.10.1=testRuntimeClasspath
biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath
ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -9,7 +8,6 @@ com.ethlo.time:itu:1.14.0=testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.luben:zstd-jni:1.5.6-10=testRuntimeClasspath
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
@@ -63,7 +61,6 @@ 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.kafka:kafka-clients:4.1.2=testRuntimeClasspath
org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -147,7 +144,6 @@ org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,te
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath
org.xerial.snappy:snappy-java:1.1.10.7=testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
@@ -1,12 +1,7 @@
package dev.caskeleton.adapter.outbound.messaging;
import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.core.MessagePublisher;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessagePublisher;
import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter;
import dev.caskeleton.adapter.outbound.messaging.outbox.Slf4jOutboxRelayFailureReportAdapter;
import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort;
@@ -17,82 +12,43 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Assembles both messaging ports onto the single active {@link MessageBroker} (the cache
* central-assembly pattern). A broker is contributed as a
* {@code @ConditionalOnProperty(app.messaging.broker=<id>)}-gated bean, at most one active — adding
* a broker is new files only and this config never changes. A broker that is set but that no bean
* contributes fails startup.
* Binds the outbox relay's publish port to the canonical platform bridge.
*
* <p>The outbox publish port has no stand-in. A stand-in that throws on every call would still
* satisfy the relay scheduler's bean condition, and the relay would exhaust every PENDING row to
* DEAD against it. So a present-and-enabled bridge with a blank broker and no canonical transport
* is refused at startup: the module is here, so messaging was wanted, and nothing can publish.
* DEAD against it. So a present-and-enabled bridge that cannot publish — no platform publisher, or
* no {@code app.messaging.producer-id} — is refused at startup: the module is here, so messaging
* was wanted, and nothing can publish.
*/
@Configuration
@EnableConfigurationProperties(MessagingSettings.class)
public class MessagingConfig {
@Bean
public MessagePublisher messagePublisher(
ObjectProvider<MessageBroker> brokerProvider,
MessagingSettings settings,
FailOpenDependencyLogger dependencyLogger) {
MessageBroker active = resolveBroker(brokerProvider, settings);
return (active == null)
? new DisabledMessagePublisher()
: new OutboundMessagePublisher(active, dependencyLogger);
}
/** The {@code dependency_name} the relay's failure log carries when no broker is named. */
static final String DEPENDENCY_NAME = "messaging-platform";
@Bean
public OutboxMessagePublishPort outboxMessagePublishPort(
ObjectProvider<MessageBroker> brokerProvider,
ObjectProvider<IntegrationEventPublishPort> canonicalPublisherProvider,
MessagingSettings settings,
@Value("${ca-skeleton.outbox.canonical-transport-enabled:false}")
boolean canonicalTransportEnabled) {
MessageBroker active = resolveBroker(brokerProvider, settings);
ObjectProvider<IntegrationEventPublishPort> canonicalPublisherProvider) {
IntegrationEventPublishPort canonicalPublisher = canonicalPublisherProvider.getIfAvailable();
if (active == null && canonicalPublisher == null) {
if (canonicalPublisher == null) {
throw new IllegalStateException(
"app.messaging.enabled is on but app.messaging.broker is blank and no canonical transport"
+ " is configured, so nothing can publish outbox rows — select a broker (the"
+ " messaging-kafka module defaults it to kafka), set app.messaging.producer-id for the"
+ " canonical transport, or set app.messaging.enabled=false");
"app.messaging.enabled is on but no IntegrationEventPublishPort exists, so nothing can"
+ " publish outbox rows — set app.messaging.producer-id and select a messaging"
+ " transport (the messaging-kafka module), or set app.messaging.enabled=false");
}
return new OutboxMessagePublishAdapter(
java.util.Optional.ofNullable(active),
java.util.Optional.ofNullable(canonicalPublisher),
canonicalTransportEnabled);
return new OutboxMessagePublishAdapter(canonicalPublisher);
}
/** Always available, including when broker publication is disabled. */
/**
* Always available while the bridge is on. The log names the broker the platform was told to use
* ({@code app.messaging.broker}, the platform's selector), so the relay's failure lines keep the
* {@code dependency_name} an alert already matches on.
*/
@Bean
public OutboxRelayFailureReportPort outboxRelayFailureReportPort(MessagingSettings settings) {
String dependencyName = settings.broker().isBlank() ? "disabled" : settings.broker();
return new Slf4jOutboxRelayFailureReportAdapter(dependencyName);
}
private static MessageBroker resolveBroker(
ObjectProvider<MessageBroker> brokerProvider, MessagingSettings settings) {
if (settings.broker().isBlank()) {
return null;
}
MessageBroker active = brokerProvider.getIfAvailable();
if (active == null) {
throw new IllegalStateException(
"app.messaging.broker="
+ settings.broker()
+ " but no MessageBroker bean contributes that id — enable the broker template"
+ " (supply its client seam) or unset app.messaging.broker");
}
if (!settings.broker().equals(active.brokerId())) {
throw new IllegalStateException(
"app.messaging.broker="
+ settings.broker()
+ " but the active MessageBroker reports brokerId '"
+ active.brokerId()
+ "'");
}
return active;
public OutboxRelayFailureReportPort outboxRelayFailureReportPort(
@Value("${app.messaging.broker:}") String broker) {
return new Slf4jOutboxRelayFailureReportAdapter(
broker.isBlank() ? DEPENDENCY_NAME : broker.trim());
}
}
@@ -1,24 +1,17 @@
package dev.caskeleton.adapter.outbound.messaging;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Messaging template selection. {@code app.messaging.broker=<brokerId>} chooses the single active
* {@link MessageBroker} (e.g. {@code kafka}). Blank means no legacy broker: the generic publisher
* is the fail-fast {@code DisabledMessagePublisher}, and startup is refused unless the canonical
* transport can publish outbox rows instead.
* The application bridge's own setting under {@code app.messaging}.
*
* @param broker the active legacy broker id, matched against {@link MessageBroker#brokerId()};
* blank means the legacy broker template is disabled
* @param producerId the explicit logical producing-service identity used by the canonical platform
* bridge; blank means that bridge is not exposed
*/
@ConfigurationProperties(prefix = "app.messaging")
public record MessagingSettings(String broker, String producerId) {
public record MessagingSettings(String producerId) {
public MessagingSettings {
broker = (broker == null) ? "" : broker.trim();
producerId = (producerId == null) ? "" : producerId.trim();
}
}
@@ -3,7 +3,6 @@ package dev.caskeleton.adapter.outbound.messaging.autoconfigure;
import dev.caskeleton.adapter.outbound.messaging.MessagingConfig;
import dev.caskeleton.adapter.outbound.messaging.MessagingSettings;
import dev.caskeleton.adapter.outbound.messaging.platformbridge.PlatformIntegrationEventPublishAdapter;
import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
import org.springframework.boot.autoconfigure.AutoConfiguration;
@@ -23,11 +22,9 @@ import org.springframework.util.StringUtils;
/**
* The one place that decides whether this application publishes to a broker.
*
* <p>Before this, whether {@code app.messaging.broker} was blank was the de-facto switch. That is a
* selector doing a switch's job, and it reads badly in both directions: a blank broker with the
* relay enabled took down startup, while a deployment that wanted no messaging at all still
* assembled settings and publishers. Broker-specific client configuration is now a build-time
* capability leaf; this root remains broker-neutral and only binds ports to a contributed broker.
* <p>The broker itself is a build-time choice: a transport leaf (messaging-kafka) brings the
* vendored platform and its transport, and this root stays broker-neutral — it binds the
* application's ports to the platform's pre-encoded publish path and nothing else.
*
* <p>On when present: an application that selected a messaging leaf wants messaging, so a missing
* {@code app.messaging.enabled} means on and only an explicit {@code false} turns it off.
@@ -43,17 +40,6 @@ import org.springframework.util.StringUtils;
@Import(MessagingConfig.class)
public class MessagingBridgeRootAutoConfiguration {
/**
* The shared fail-open logger the publisher needs, so the module works wherever it is present
* rather than only where a composition root's component scan happens to reach {@code
* adapter.support}. Backs off to the one that scan registers.
*/
@Bean
@ConditionalOnMissingBean
FailOpenDependencyLogger failOpenDependencyLogger() {
return new FailOpenDependencyLogger();
}
/**
* Connects canonical application integration events to the central messaging platform.
*
@@ -1,17 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.core;
import dev.caskeleton.shared.error.AdapterDisabledException;
/**
* Fail-fast {@link MessagePublisher} binding when no broker is active ({@code app.messaging.broker}
* unset — the default). Any publish throws {@link AdapterDisabledException} — never a silent no-op
* (mirrors the cache router's unbound fail-fast). Broker-agnostic; the outbox counterpart is {@code
* DisabledOutboxMessagePublisher}.
*/
public class DisabledMessagePublisher implements MessagePublisher {
@Override
public void publish(OutboundMessage message) {
throw new AdapterDisabledException("messaging");
}
}
@@ -1,20 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.core;
/**
* SPI a forking project contributes to bind the messaging template to a real broker. The active
* broker is selected by {@code app.messaging.broker=<brokerId>}. The skeleton carries no broker SDK
* — it is supplied by the project that selects the broker.
*/
public interface MessageBroker {
/** Stable broker identifier matched against {@code app.messaging.broker}. */
String brokerId();
/**
* Sends a message to the broker. May throw on any transport/broker failure; the binding decorator
* applies the fail-open (general) or fail-closed (outbox) policy.
*
* @throws Exception on any send failure (handled by the binding decorator)
*/
void send(OutboundMessage message) throws Exception;
}
@@ -1,13 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.core;
/**
* Adapter-local fire-and-forget (fail-open) publishing port for the optional adapter template. Not
* use-case-facing ({@code adapter-outbound} type, so application-core cannot hold it) — a use case
* that needs durable delivery uses the application-core {@code OutboxMessagePublishPort}. The
* active binding is selected by {@code app.messaging.broker}. The {@code void} return keeps broker
* SDK types from escaping the adapter (B7).
*/
public interface MessagePublisher {
void publish(OutboundMessage message);
}
@@ -1,25 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.core;
import java.util.Objects;
/**
* Transport-neutral message a {@link MessagePublisher} emits. Carries only the routing key family
* ({@code topic}, partition {@code key}) and an already-serialized {@code payload} string — it
* deliberately does NOT depend on any broker SDK type, so the messaging port stays
* template-portable across Kafka and any future broker.
*
* @param topic logical destination / topic
* @param key partition / ordering key (may be empty, never null)
* @param payload serialized message body (the producer is responsible for serialization)
*/
public record OutboundMessage(String topic, String key, String payload) {
public OutboundMessage {
Objects.requireNonNull(topic, "topic");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(payload, "payload");
if (topic.isBlank()) {
throw new IllegalArgumentException("topic must not be blank");
}
}
}
@@ -1,65 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.core;
import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger;
/**
* General {@link MessagePublisher} binding (fail-open). Delegates to the active {@link
* MessageBroker}; on failure it logs with the correlation id and swallows — a broker outage must
* never turn a core use case into a 5xx (durable delivery is delegated to the outbox/retry path).
* The fail-closed counterpart is {@code OutboxMessagePublishAdapter}.
*
* <p>Broker-agnostic: the same decorator serves any {@link MessageBroker}, so adding a broker never
* touches this class.
*/
public class OutboundMessagePublisher implements MessagePublisher {
private static final String DEPENDENCY_TYPE = "messaging";
private final MessageBroker broker;
private final FailOpenDependencyLogger dependencyLogger;
public OutboundMessagePublisher(MessageBroker broker, FailOpenDependencyLogger dependencyLogger) {
this.broker = broker;
this.dependencyLogger = dependencyLogger;
}
@Override
public void publish(OutboundMessage message) {
// The send and the observation are separate steps because they used to share a try block: a
// logger that threw after a successful send was caught by the same catch and reported as a
// publish failure. The broker had accepted the message; the only thing that failed was the
// record of it, and the two must not be confusable.
boolean sent = false;
try {
broker.send(message);
sent = true;
} catch (Exception ex) {
// fail-open: observe with correlationId, delegate durability to outbox/retry,
// do NOT propagate — the core use case must still succeed. The failure is swallowed, the
// interrupt is not: a thread being stopped must still see it after this returns.
if (ex instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
observeQuietly(
() -> dependencyLogger.logFailure(broker.brokerId(), DEPENDENCY_TYPE, "publish", ex));
}
if (sent) {
observeQuietly(
() -> dependencyLogger.logSuccess(broker.brokerId(), DEPENDENCY_TYPE, "publish"));
}
}
/**
* Runs an observation, absorbing whatever it throws.
*
* <p>Diagnostics are non-authoritative. An appender that is out of disk must not change what the
* caller believes about the broker.
*/
private static void observeQuietly(Runnable observation) {
try {
observation.run();
} catch (RuntimeException ignored) {
// Nothing to report it to: the reporter is what failed.
}
}
}
@@ -1,70 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.outbox;
import dev.caskeleton.application.outbox.OutboxEvent;
/**
* Hand-rolled, dependency-free JSON serialiser for the outbox envelope (no Jackson — the module
* deliberately keeps {@code jackson-databind} off its classpath).
*
* <p>{@link OutboxEvent#payload()} MUST already be a valid serialised JSON value; it is inserted
* verbatim (no escaping) — serialisation policy is owned by the {@code schema-serialization}
* branch, this class only assembles the envelope. All other string fields go through {@link
* #escape(String)}.
*/
public final class OutboxEnvelopeJson {
private OutboxEnvelopeJson() {}
public static String toJson(OutboxEvent event) {
return "{"
+ "\"eventId\":\""
+ escape(event.eventId())
+ "\","
+ "\"eventType\":\""
+ escape(event.eventType())
+ "\","
+ "\"aggregateId\":\""
+ escape(event.aggregateId())
+ "\","
+ "\"occurredAt\":\""
+ escape(event.occurredAt().toString())
+ "\","
+ "\"correlationId\":\""
+ escape(event.correlationId())
+ "\","
+ "\"idempotencyKey\":\""
+ escape(event.idempotencyKey())
+ "\","
+ "\"payload\":"
+ event.payload()
+ "}";
}
/** Escapes a string for a JSON string literal (RFC 8259 §7). */
static String escape(String value) {
StringBuilder sb = new StringBuilder(value.length() + 4);
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (c == '\\') {
sb.append("\\\\");
} else if (c == '"') {
sb.append("\\\"");
} else if (c == '\b') {
sb.append("\\b");
} else if (c == '\t') {
sb.append("\\t");
} else if (c == '\n') {
sb.append("\\n");
} else if (c == '\f') {
sb.append("\\f");
} else if (c == '\r') {
sb.append("\\r");
} else if (c < 0x20) {
sb.append(String.format("\\u%04x", (int) c));
} else {
sb.append(c);
}
}
return sb.toString();
}
}
@@ -1,56 +1,28 @@
package dev.caskeleton.adapter.outbound.messaging.outbox;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent;
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxEvent;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException;
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
import dev.caskeleton.application.outbox.OutboxPublishRefusedException;
import dev.caskeleton.shared.error.AdapterDisabledException;
import java.util.Objects;
import java.util.Optional;
/**
* Transport-only cutover router for the legacy outbox relay authority.
* The relay's publish port: a claimed row's validated event, delegated unchanged to the canonical
* {@link IntegrationEventPublishPort}.
*
* <p>Legacy rows are rendered through the existing {@link MessageBroker} path. Canonical rows carry
* an already validated event and are delegated unchanged to {@link IntegrationEventPublishPort}. A
* row never falls back across branches when its required transport is absent.
* <p>The event is the one the append validated, restored from its exact envelope bytes; nothing
* here re-renders it. The platform's four-valued outcome is passed through, so the relay can tell a
* possibly-stored message (ambiguous) from a refused one.
*/
public final class OutboxMessagePublishAdapter implements OutboxMessagePublishPort {
private final Optional<MessageBroker> broker;
private final Optional<IntegrationEventPublishPort> canonicalPublisher;
private final boolean canonicalTransportEnabled;
private final IntegrationEventPublishPort canonicalPublisher;
public OutboxMessagePublishAdapter(MessageBroker broker) {
this(
Optional.of(Objects.requireNonNull(broker, "broker must not be null")),
Optional.empty(),
false);
}
public OutboxMessagePublishAdapter(
Optional<MessageBroker> broker, Optional<IntegrationEventPublishPort> canonicalPublisher) {
this(broker, canonicalPublisher, true);
}
public OutboxMessagePublishAdapter(
Optional<MessageBroker> broker,
Optional<IntegrationEventPublishPort> canonicalPublisher,
boolean canonicalTransportEnabled) {
this.broker = Objects.requireNonNull(broker, "broker Optional must not be null");
public OutboxMessagePublishAdapter(IntegrationEventPublishPort canonicalPublisher) {
this.canonicalPublisher =
Objects.requireNonNull(canonicalPublisher, "canonicalPublisher Optional must not be null");
this.canonicalTransportEnabled = canonicalTransportEnabled;
if (broker.isEmpty() && canonicalPublisher.isEmpty()) {
throw new IllegalArgumentException(
"at least one outbox publication transport must be present");
}
Objects.requireNonNull(canonicalPublisher, "canonicalPublisher must not be null");
}
@Override
@@ -68,38 +40,6 @@ public final class OutboxMessagePublishAdapter implements OutboxMessagePublishPo
@Override
public OutboxPublishOutcome publishForOutcome(ClaimedOutboxEvent event) {
Objects.requireNonNull(event, "event must not be null");
if (event instanceof CanonicalClaimedOutboxEvent canonical) {
if (!canonicalTransportEnabled) {
throw new AdapterDisabledException("messaging canonical platform transport");
}
IntegrationEventPublishPort publisher =
canonicalPublisher.orElseThrow(
() -> new AdapterDisabledException("messaging canonical platform"));
return publisher.publish(canonical.event()).toCompletableFuture().join();
}
if (event instanceof OutboxEvent legacy) {
return publishLegacy(legacy);
}
throw new IllegalStateException("unsupported claimed outbox event type: " + event.getClass());
}
private OutboxPublishOutcome publishLegacy(OutboxEvent event) {
MessageBroker activeBroker =
broker.orElseThrow(() -> new AdapterDisabledException("messaging legacy broker"));
String envelope = OutboxEnvelopeJson.toJson(event);
OutboundMessage message = new OutboundMessage(event.eventType(), event.aggregateId(), envelope);
try {
activeBroker.send(message);
return OutboxPublishOutcome.CONFIRMED;
} catch (Exception unknownOutcome) {
// The legacy MessageBroker seam exposes no transmission evidence. Once send() throws, this
// adapter cannot prove that zero bytes reached the broker, so calling it a refusal risks
// losing an event that was accepted before the acknowledgement path failed. An interrupt is
// kept, so a relay being shut down stops instead of moving on to the next row.
if (unknownOutcome instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
return OutboxPublishOutcome.AMBIGUOUS;
}
return canonicalPublisher.publish(event.event()).toCompletableFuture().join();
}
}
@@ -1,95 +1,42 @@
package dev.caskeleton.adapter.outbound.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaAdapterConfig;
import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaSender;
import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger;
import dev.caskeleton.adapter.outbound.messaging.outbox.OutboxMessagePublishAdapter;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class MessagingConfigTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new)
.withUserConfiguration(MessagingConfig.class);
new ApplicationContextRunner().withUserConfiguration(MessagingConfig.class);
@Test
void blankBrokerWithoutCanonicalTransportIsRefusedRatherThanStoodIn() {
void noCanonicalPublisherIsRefusedRatherThanStoodIn() {
// A stand-in outbox publisher would satisfy the relay scheduler's bean condition and drain
// every
// PENDING row to DEAD. With nothing to publish to, the bridge refuses startup instead.
runner
.withPropertyValues("app.messaging.broker=")
.run(
context -> {
assertThat(context).hasFailed();
assertThat(rootCause(context.getStartupFailure()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("app.messaging.broker is blank")
.hasMessageContaining("app.messaging.enabled=false");
});
// every PENDING row to DEAD. With nothing to publish to, the bridge refuses startup instead.
runner.run(
context ->
assertThat(rootCause(context.getStartupFailure()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("no IntegrationEventPublishPort exists")
.hasMessageContaining("app.messaging.producer-id"));
}
@Test
void selectedKafkaBrokerWithoutProjectSenderFailsStartupCharacterization() {
void theOutboxPublishPortDelegatesToTheCanonicalPublisher() {
runner
.withUserConfiguration(KafkaAdapterConfig.class)
.withPropertyValues(
"app.messaging.broker=kafka", "app.messaging.kafka.brokers=localhost:9092")
.run(
context -> {
assertThat(context).hasFailed();
assertThat(rootCause(context.getStartupFailure()))
.isInstanceOf(NoSuchBeanDefinitionException.class)
.hasMessageContaining(KafkaSender.class.getName());
});
}
@Test
void selectedBrokerIdMismatchFailsStartupCharacterization() {
runner
.withBean(MessageBroker.class, () -> brokerReporting("other"))
.withPropertyValues("app.messaging.broker=kafka")
.withBean(
IntegrationEventPublishPort.class,
() -> event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED))
.run(
context ->
assertThat(context)
.hasFailed()
.getFailure()
.hasRootCauseMessage(
"app.messaging.broker=kafka but the active MessageBroker reports brokerId"
+ " 'other'"));
}
@Test
void theDisabledPublisherFailsFastNamingMessaging() {
assertThatThrownBy(
() ->
new DisabledMessagePublisher()
.publish(
new dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage(
"t", "k", "p")))
.isInstanceOf(dev.caskeleton.shared.error.AdapterDisabledException.class)
.extracting("adapterName")
.isEqualTo("messaging");
}
private static MessageBroker brokerReporting(String brokerId) {
return new MessageBroker() {
@Override
public String brokerId() {
return brokerId;
}
@Override
public void send(
dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage ignoredMessage) {}
};
assertThat(context.getBean(OutboxMessagePublishPort.class))
.isInstanceOf(OutboxMessagePublishAdapter.class));
}
private static Throwable rootCause(Throwable failure) {
@@ -3,9 +3,6 @@ package dev.caskeleton.adapter.outbound.messaging.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.messaging.MessagingSettings;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.messaging.schema.EncodedMessagePublisher;
@@ -20,25 +17,26 @@ class MessagingPlatformBridgeAutoConfigurationTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MessagingBridgeRootAutoConfiguration.class))
.withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new)
.withBean(
EncodedMessagePublisher.class,
() ->
(destination, message, options) -> {
throw new AssertionError("publisher is not invoked while wiring the bridge");
})
.withBean(MessageBroker.class, MessagingPlatformBridgeAutoConfigurationTest::testBroker)
.withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=test");
.withPropertyValues("app.messaging.enabled=true");
@Test
void explicitProducerIdCreatesOneCanonicalPublishBridge() {
runner
.withPropertyValues("app.messaging.producer-id=portfolio-service")
.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).hasSingleBean(IntegrationEventPublishPort.class);
});
.run(context -> assertThat(context).hasSingleBean(IntegrationEventPublishPort.class));
}
@Test
void explicitProducerIdGivesTheRelayItsPublishPort() {
runner
.withPropertyValues("app.messaging.producer-id=portfolio-service")
.run(context -> assertThat(context).hasSingleBean(OutboxMessagePublishPort.class));
}
@Test
@@ -51,7 +49,6 @@ class MessagingPlatformBridgeAutoConfigurationTest {
MessagingBridgeRootAutoConfiguration.class,
dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration
.class))
.withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new)
.withPropertyValues(
"app.messaging.enabled=true", "app.messaging.producer-id=portfolio-service");
@@ -59,28 +56,23 @@ class MessagingPlatformBridgeAutoConfigurationTest {
assembled.run(context -> assertThat(context).hasSingleBean(IntegrationEventPublishPort.class));
}
/**
* The shipped yml always defines the key ({@code ${APP_MESSAGING_PRODUCER_ID:}}), so the property
* is present and blank whenever the operator has not set it. Blank means no bridge is built — the
* identity is never guessed — and with no bridge nothing can publish, so a module that is present
* and on refuses to start rather than leave the relay without a transport.
*/
@ParameterizedTest
@ValueSource(strings = {"", " "})
void blankProducerIdLeavesTheBridgeOutWithoutFailingStartup(String producerId) {
// The shipped yml always defines the key (`${APP_MESSAGING_PRODUCER_ID:}`), so the property is
// present and blank whenever the operator has not set it.
void blankProducerIdRefusesStartupInsteadOfInventingAnIdentity(String producerId) {
runner
.withPropertyValues("app.messaging.producer-id=" + producerId)
.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class);
});
}
@Test
void presentWithoutTheSwitchIsOn() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(MessagingBridgeRootAutoConfiguration.class))
.withBean(FailOpenDependencyLogger.class, FailOpenDependencyLogger::new)
.withBean(MessageBroker.class, MessagingPlatformBridgeAutoConfigurationTest::testBroker)
.withPropertyValues("app.messaging.broker=test")
.run(context -> assertThat(context).hasSingleBean(OutboxMessagePublishPort.class));
context ->
assertThat(context)
.getFailure()
.rootCause()
.hasMessageContaining("no IntegrationEventPublishPort exists"));
}
@Test
@@ -94,26 +86,4 @@ class MessagingPlatformBridgeAutoConfigurationTest {
assertThat(context).doesNotHaveBean(OutboxMessagePublishPort.class);
});
}
@Test
void missingProducerIdDoesNotInventCanonicalPublisherIdentity() {
runner.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class);
});
}
/** A selected broker, so the bridge has something to publish outbox rows to. */
private static MessageBroker testBroker() {
return new MessageBroker() {
@Override
public String brokerId() {
return "test";
}
@Override
public void send(OutboundMessage message) {}
};
}
}
@@ -1,175 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.core;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger;
import dev.caskeleton.adapter.outbound.support.OutboundCorrelation;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
/**
* General {@link OutboundMessagePublisher} = fail-open: delegates to the active {@link
* MessageBroker}; a broker failure is logged with the correlation id and swallowed (never
* propagated). Broker-agnostic — a fake broker stands in for any real broker.
*/
class OutboundMessagePublisherTest {
private ch.qos.logback.classic.Logger logbackLogger;
private ListAppender<ILoggingEvent> appender;
private FailOpenDependencyLogger dependencyLogger;
@BeforeEach
void setUp() {
logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("test.messaging");
appender = new ListAppender<>();
appender.start();
logbackLogger.addAppender(appender);
logbackLogger.setLevel(Level.DEBUG);
dependencyLogger = new FailOpenDependencyLogger(logbackLogger);
}
@AfterEach
void tearDown() {
logbackLogger.detachAppender(appender);
MDC.clear();
}
/** Fake broker (brokerId "kafka") capturing sends, optionally failing. */
private static final class FakeBroker implements MessageBroker {
final List<OutboundMessage> sent = new ArrayList<>();
private final RuntimeException failure;
FakeBroker() {
this.failure = null;
}
FakeBroker(RuntimeException failure) {
this.failure = failure;
}
@Override
public String brokerId() {
return "kafka";
}
@Override
public void send(OutboundMessage message) {
if (failure != null) {
throw failure;
}
sent.add(message);
}
}
@Test
void publishDelegatesToTheActiveBrokerOnSuccess() {
FakeBroker broker = new FakeBroker();
OutboundMessagePublisher publisher = new OutboundMessagePublisher(broker, dependencyLogger);
OutboundMessage message = new OutboundMessage("worklog-events", "wl-1", "{}");
publisher.publish(message);
assertThat(broker.sent).containsExactly(message);
}
@Test
void publishFailureIsFailOpenAndNeverThrows() {
FakeBroker broker = new FakeBroker(new IllegalStateException("broker unavailable"));
OutboundMessagePublisher publisher = new OutboundMessagePublisher(broker, dependencyLogger);
// fail-open: a broker outage must not propagate to the core use case.
assertThatCode(() -> publisher.publish(new OutboundMessage("t", "k", "p")))
.doesNotThrowAnyException();
}
/**
* Fail-open swallows the failure, not the interrupt: a thread being stopped must still see that
* it is being stopped after the publish returns.
*/
@Test
void anInterruptedSendIsSwallowedWithTheInterruptFlagKept() {
// given
MessageBroker interruptedBroker =
new MessageBroker() {
@Override
public String brokerId() {
return "kafka";
}
@Override
public void send(OutboundMessage message) throws InterruptedException {
throw new InterruptedException("shutting down");
}
};
OutboundMessagePublisher publisher =
new OutboundMessagePublisher(interruptedBroker, dependencyLogger);
// when
publisher.publish(new OutboundMessage("t", "k", "p"));
// then
assertThat(Thread.interrupted()).isTrue();
}
@Test
void publishFailureLogCarriesCorrelationIdAndBrokerId() {
MDC.put(OutboundCorrelation.MDC_KEY, "corr-msg-1");
FakeBroker broker = new FakeBroker(new IllegalStateException("broker unavailable"));
OutboundMessagePublisher publisher = new OutboundMessagePublisher(broker, dependencyLogger);
publisher.publish(new OutboundMessage("t", "k", "p"));
ILoggingEvent event =
appender.list.stream().filter(e -> e.getLevel() == Level.WARN).findFirst().orElseThrow();
assertThat(event.getFormattedMessage())
.contains("correlation_id=\"corr-msg-1\"")
.contains("dependency_name=\"kafka\"")
.contains("dependency_type=\"messaging\"")
.contains("operation=\"publish\"");
}
@org.junit.jupiter.api.DisplayName(
"a logger failure after a confirmed send is not a publish failure")
@Test
void aLoggerFailureAfterAConfirmedSendIsNotAPublishFailure() {
// The send and the success log used to share one try block, so a logger that threw after the
// broker had accepted the message was caught by the failure branch and recorded as a publish
// failure. The broker's outcome and the record of it are different facts.
FakeBroker broker = new FakeBroker();
org.slf4j.Logger throwingLogger =
(org.slf4j.Logger)
java.lang.reflect.Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class<?>[] {org.slf4j.Logger.class},
(proxy, method, args) -> {
if (method.getName().equals("debug")) {
throw new IllegalStateException("the appender is out of disk");
}
if (method.getReturnType() == boolean.class) {
return true;
}
if (method.getReturnType() == String.class) {
return "test.messaging";
}
return null;
});
OutboundMessagePublisher publisher =
new OutboundMessagePublisher(broker, new FailOpenDependencyLogger(throwingLogger));
OutboundMessage message = new OutboundMessage("worklog-events", "wl-1", "{}");
assertThatCode(() -> publisher.publish(message)).doesNotThrowAnyException();
assertThat(broker.sent)
.as("the message reached the broker; only the record of it failed")
.containsExactly(message);
}
}
@@ -1,166 +0,0 @@
package dev.caskeleton.adapter.outbound.messaging.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxEvent;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
import dev.caskeleton.shared.error.AdapterDisabledException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
class OutboxCanonicalPublishRoutingTest {
@Test
void canonicalClaimUsesOnlyCanonicalPublisherAndPreservesExactEvent() {
RecordingBroker broker = new RecordingBroker();
RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher();
canonical.result = OutboxPublishOutcome.AMBIGUOUS;
OutboxMessagePublishAdapter adapter =
new OutboxMessagePublishAdapter(Optional.of(broker), Optional.of(canonical));
CanonicalClaimedOutboxEvent claim =
new CanonicalClaimedOutboxEvent(canonicalEvent(), OutboxEventStatus.IN_FLIGHT, 1);
OutboxPublishOutcome outcome = adapter.publishForOutcome(claim);
assertThat(outcome).isEqualTo(OutboxPublishOutcome.AMBIGUOUS);
assertThat(canonical.events).containsExactly(claim.event());
assertThat(broker.sent).isEmpty();
assertThat(canonical.events.getFirst().envelopeBytes())
.containsExactly(claim.event().envelopeBytes());
}
@Test
void legacyClaimUsesOnlyLegacyBroker() {
RecordingBroker broker = new RecordingBroker();
RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher();
OutboxMessagePublishAdapter adapter =
new OutboxMessagePublishAdapter(Optional.of(broker), Optional.of(canonical));
OutboxPublishOutcome outcome = adapter.publishForOutcome(legacyEvent());
assertThat(outcome).isEqualTo(OutboxPublishOutcome.CONFIRMED);
assertThat(broker.sent).hasSize(1);
assertThat(canonical.events).isEmpty();
}
@Test
void disabledCanonicalTransportRejectsCanonicalClaimEvenWhenPublisherExists() {
RecordingBroker broker = new RecordingBroker();
RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher();
OutboxMessagePublishAdapter adapter =
new OutboxMessagePublishAdapter(Optional.of(broker), Optional.of(canonical), false);
assertThatThrownBy(
() ->
adapter.publishForOutcome(
new CanonicalClaimedOutboxEvent(
canonicalEvent(), OutboxEventStatus.IN_FLIGHT, 1)))
.isInstanceOf(AdapterDisabledException.class)
.hasMessageContaining("canonical");
assertThat(canonical.events).isEmpty();
assertThat(broker.sent).isEmpty();
}
@Test
void missingBranchDependencyFailsClosedWithoutFallingAcrossTransports() {
OutboxMessagePublishAdapter canonicalOnly =
new OutboxMessagePublishAdapter(
Optional.empty(), Optional.of(new RecordingCanonicalPublisher()));
OutboxMessagePublishAdapter legacyOnly =
new OutboxMessagePublishAdapter(Optional.of(new RecordingBroker()), Optional.empty());
assertThatThrownBy(() -> canonicalOnly.publishForOutcome(legacyEvent()))
.isInstanceOf(AdapterDisabledException.class);
assertThatThrownBy(
() ->
legacyOnly.publishForOutcome(
new CanonicalClaimedOutboxEvent(
canonicalEvent(), OutboxEventStatus.IN_FLIGHT, 1)))
.isInstanceOf(AdapterDisabledException.class);
}
private static OutboxEvent legacyEvent() {
return new OutboxEvent(
"legacy-1",
"LegacyEvent",
"aggregate-1",
"{}",
Instant.parse("2026-09-18T03:00:00Z"),
"corr-1",
"legacy-1",
OutboxEventStatus.IN_FLIGHT,
1);
}
private static ValidatedIntegrationEvent canonicalEvent() {
String partition = "a".repeat(64);
byte[] envelope = "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8);
Sha256 zero = new Sha256(new byte[32]);
return new ValidatedIntegrationEvent(
new EventId("01994e11-4d88-7000-8000-000000000001"),
new ContractId("portfolio.worklog.reserved"),
1,
3,
new LogicalDestinationId("portfolio-domain-events"),
new AggregateIdentity("tenant-a", "worklog", "worklog-42"),
new AggregateOrder(17, 2),
Instant.parse("2026-09-18T03:00:00Z"),
"corr-1",
Optional.empty(),
partition,
partition.getBytes(StandardCharsets.US_ASCII),
envelope,
"application/json",
zero,
Sha256.of(envelope),
zero,
zero,
"catalog-r1",
"binding-r1");
}
private static final class RecordingBroker implements MessageBroker {
private final List<OutboundMessage> sent = new ArrayList<>();
@Override
public String brokerId() {
return "kafka";
}
@Override
public void send(OutboundMessage message) {
sent.add(message);
}
}
private static final class RecordingCanonicalPublisher implements IntegrationEventPublishPort {
private final List<ValidatedIntegrationEvent> events = new ArrayList<>();
private OutboxPublishOutcome result = OutboxPublishOutcome.CONFIRMED;
@Override
public java.util.concurrent.CompletionStage<OutboxPublishOutcome> publish(
ValidatedIntegrationEvent event) {
events.add(event);
return CompletableFuture.completedFuture(result);
}
}
}
@@ -1,245 +1,123 @@
package dev.caskeleton.adapter.outbound.messaging.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.outbound.messaging.core.MessageBroker;
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
import dev.caskeleton.adapter.outbound.support.FailOpenDependencyLogger;
import dev.caskeleton.application.outbox.OutboxEvent;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import java.io.IOException;
import dev.caskeleton.application.outbox.OutboxPublishAmbiguousException;
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
import dev.caskeleton.application.outbox.OutboxPublishRefusedException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Nested;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
/**
* Broker-agnostic outbox publish adapter (fail-closed). Covers:
*
* <ul>
* <li>Success — correct OutboundMessage (topic=eventType, key=aggregateId, payload=envelope JSON)
* sent to the active broker.
* <li>Fail-closed — broker failure is propagated without duplicate dependency logs; checked
* exceptions are wrapped.
* <li>Envelope JSON fields and escaping.
* </ul>
*/
class OutboxMessagePublishAdapterTest {
/** Fake broker (brokerId "kafka") capturing sends, optionally failing with a given throwable. */
private static final class FakeBroker implements MessageBroker {
final List<OutboundMessage> sent = new ArrayList<>();
private final Exception failure;
private final RecordingCanonicalPublisher canonical = new RecordingCanonicalPublisher();
private final OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(canonical);
FakeBroker() {
this.failure = null;
}
@Test
void aClaimedRowIsPublishedAsTheExactValidatedEventItCarries() {
// given
ClaimedOutboxEvent claim = claim();
FakeBroker(Exception failure) {
this.failure = failure;
}
// when
adapter.publishForOutcome(claim);
// then
assertThat(canonical.events).containsExactly(claim.event());
}
@Test
void thePlatformOutcomeIsPassedThroughUnchanged() {
// given
canonical.result = OutboxPublishOutcome.REJECTED_AFTER_BROKER;
// when
OutboxPublishOutcome outcome = adapter.publishForOutcome(claim());
// then
assertThat(outcome).isEqualTo(OutboxPublishOutcome.REJECTED_AFTER_BROKER);
}
@Test
void anAmbiguousPublishThrowsTheAmbiguousSignalFromTheThrowingMethod() {
// given
canonical.result = OutboxPublishOutcome.AMBIGUOUS;
// when
Throwable thrown = catchThrowable(() -> adapter.publish(claim()));
// then
assertThat(thrown).isInstanceOf(OutboxPublishAmbiguousException.class);
}
@Test
void aRefusedPublishThrowsTheRefusalWithItsOutcome() {
// given
canonical.result = OutboxPublishOutcome.REJECTED_BEFORE_SEND;
// when
Throwable thrown = catchThrowable(() -> adapter.publish(claim()));
// then
assertThat(thrown)
.isInstanceOf(OutboxPublishRefusedException.class)
.extracting("outcome")
.isEqualTo(OutboxPublishOutcome.REJECTED_BEFORE_SEND);
}
private static ClaimedOutboxEvent claim() {
String partition = "a".repeat(64);
byte[] envelope = "{\"wire\":\"exact\"}".getBytes(StandardCharsets.UTF_8);
Sha256 zero = new Sha256(new byte[32]);
ValidatedIntegrationEvent event =
new ValidatedIntegrationEvent(
new EventId("01994e11-4d88-7000-8000-000000000001"),
new ContractId("portfolio.worklog.reserved"),
1,
1,
new LogicalDestinationId("portfolio-domain-events"),
new AggregateIdentity("tenant-a", "worklog", "worklog-42"),
new AggregateOrder(17, 2),
Instant.parse("2026-09-18T03:00:00Z"),
"corr-1",
Optional.empty(),
partition,
partition.getBytes(StandardCharsets.US_ASCII),
envelope,
"application/json",
zero,
Sha256.of(envelope),
zero,
zero,
"catalog-r1",
"binding-r1");
return new ClaimedOutboxEvent(event, OutboxEventStatus.IN_FLIGHT, 1);
}
private static final class RecordingCanonicalPublisher implements IntegrationEventPublishPort {
private final List<ValidatedIntegrationEvent> events = new ArrayList<>();
private OutboxPublishOutcome result = OutboxPublishOutcome.CONFIRMED;
@Override
public String brokerId() {
return "kafka";
}
@Override
public void send(OutboundMessage message) throws Exception {
if (failure != null) {
throw failure;
}
sent.add(message);
}
}
private OutboxEvent sampleEvent() {
return new OutboxEvent(
"evt-01",
"WorkLogReserved",
"wl-agg-1",
"{\"workLogId\":\"wl-01\"}",
Instant.parse("2024-01-02T03:04:05Z"),
"corr-abc",
"idem-xyz",
OutboxEventStatus.IN_FLIGHT,
1);
}
@Nested
class SuccessPath {
@Test
void legacyVoidSenderNormalReturnCompletesWithoutBrokerConfirmationCharacterization() {
FakeBroker broker = new FakeBroker();
OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker);
adapter.publish(sampleEvent());
assertThat(broker.sent).hasSize(1);
OutboundMessage sent = broker.sent.get(0);
assertThat(sent.topic()).isEqualTo("WorkLogReserved");
assertThat(sent.key()).isEqualTo("wl-agg-1");
}
@Test
void publishEnvelopeContainsAllFields() {
FakeBroker broker = new FakeBroker();
OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker);
adapter.publish(sampleEvent());
String payload = broker.sent.get(0).payload();
assertThat(payload).contains("\"eventId\"");
assertThat(payload).contains("\"eventType\"");
assertThat(payload).contains("\"aggregateId\"");
assertThat(payload).contains("\"occurredAt\"");
assertThat(payload).contains("\"correlationId\"");
assertThat(payload).contains("\"idempotencyKey\"");
assertThat(payload).contains("\"payload\"");
}
@Test
void publishEnvelopeFieldValuesMatchEvent() {
FakeBroker broker = new FakeBroker();
OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker);
adapter.publish(sampleEvent());
String payload = broker.sent.get(0).payload();
assertThat(payload).contains("\"evt-01\"");
assertThat(payload).contains("\"WorkLogReserved\"");
assertThat(payload).contains("\"wl-agg-1\"");
assertThat(payload).contains("2024-01-02T03:04:05Z");
assertThat(payload).contains("\"corr-abc\"");
assertThat(payload).contains("\"idem-xyz\"");
assertThat(payload).contains("{\"workLogId\":\"wl-01\"}");
}
}
@Nested
class FailClosedPath {
@Test
void senderFailureIsTypedAsAmbiguousWhenTheLegacySeamHasNoTransmissionEvidence() {
FakeBroker broker = new FakeBroker(new IllegalStateException("broker down"));
OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker);
assertThatThrownBy(() -> adapter.publish(sampleEvent()))
.isInstanceOf(dev.caskeleton.application.outbox.OutboxPublishAmbiguousException.class);
assertThat(adapter.publishForOutcome(sampleEvent()))
.isEqualTo(dev.caskeleton.application.outbox.OutboxPublishOutcome.AMBIGUOUS);
}
@Test
void publishFailureEmitsNoDuplicateDependencyLog() {
ch.qos.logback.classic.Logger dependencyLogger =
(ch.qos.logback.classic.Logger) LoggerFactory.getLogger(FailOpenDependencyLogger.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
dependencyLogger.addAppender(appender);
dependencyLogger.setLevel(Level.DEBUG);
FakeBroker broker = new FakeBroker(new IllegalStateException("broker unavailable"));
OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker);
try {
adapter.publish(sampleEvent());
} catch (RuntimeException ignored) {
// expected
} finally {
dependencyLogger.detachAppender(appender);
appender.stop();
}
assertThat(appender.list).isEmpty();
}
@Test
void checkedNetworkFailureIsAlsoAmbiguousRatherThanAnUntypedRuntimeException() {
FakeBroker broker = new FakeBroker(new IOException("network error"));
OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker);
assertThatThrownBy(() -> adapter.publish(sampleEvent()))
.isInstanceOf(dev.caskeleton.application.outbox.OutboxPublishAmbiguousException.class);
}
/**
* A relay stopped mid-send stays stopped.
*
* <p>The interrupt was consumed by the catch that turns a failed send into AMBIGUOUS, so a
* relay being shut down went on to the next row and waited out that row's acknowledgement
* timeout too.
*/
@Test
void anInterruptedSendKeepsTheRelayThreadInterrupted() {
// given
FakeBroker broker = new FakeBroker(new InterruptedException("shutting down"));
OutboxMessagePublishAdapter adapter = new OutboxMessagePublishAdapter(broker);
// when
adapter.publishForOutcome(sampleEvent());
// then
assertThat(Thread.interrupted()).isTrue();
}
@Test
void adapterStateContainsOnlyTheTwoTransportReferencesAndCanonicalGate() {
assertThat(
Arrays.stream(OutboxMessagePublishAdapter.class.getDeclaredFields())
.map(field -> field.getName()))
.containsExactlyInAnyOrder("broker", "canonicalPublisher", "canonicalTransportEnabled");
}
}
@Nested
class JsonEscape {
@Test
void envelopeEscapesDoubleQuotesInStringFields() {
OutboxEvent eventWithQuote =
new OutboxEvent(
"evt-02",
"Has\"Quote",
"agg-1",
"{}",
Instant.parse("2024-01-01T00:00:00Z"),
"corr-1",
"idem-1",
OutboxEventStatus.IN_FLIGHT,
1);
FakeBroker broker = new FakeBroker();
new OutboxMessagePublishAdapter(broker).publish(eventWithQuote);
assertThat(broker.sent.get(0).payload()).contains("Has\\\"Quote");
}
@Test
void envelopeInsertsPayloadRawWithoutDoubleEncoding() {
OutboxEvent event =
new OutboxEvent(
"evt-05",
"SomeEvent",
"agg-2",
"{\"nested\":{\"a\":1}}",
Instant.parse("2024-01-01T00:00:00Z"),
"corr-2",
"idem-2",
OutboxEventStatus.IN_FLIGHT,
1);
FakeBroker broker = new FakeBroker();
new OutboxMessagePublishAdapter(broker).publish(event);
String payload = broker.sent.get(0).payload();
assertThat(payload).contains("{\"nested\":{\"a\":1}}");
assertThat(payload).doesNotContain("\"{\\\"nested\\\"");
public CompletionStage<OutboxPublishOutcome> publish(ValidatedIntegrationEvent event) {
events.add(event);
return CompletableFuture.completedFuture(result);
}
}
}
+13 -5
View File
@@ -66,7 +66,7 @@ to `spring.autoconfigure.exclude`, so no DataSource, pool, EntityManagerFactory
The same split applies to owner-safe PostgreSQL idempotency: this leaf constructs the concrete
PostgreSQL store behind `IdempotencyStorePort` (`PostgreSqlIdempotencyStoreConfig`, active only with
`ca-skeleton.capabilities.idempotency.provider=postgresql`), while app-bootstrap owns provider
`ca-skeleton.capabilities.idempotency.provider=postgresql`), while `composition:idempotency` owns provider
selection, TTL/lease/codec policy, executor construction, and exclusivity validation. With that
provider the leaf also applies the `db/migration/jpa/core` + `db/migration/jpa/idempotency` Flyway
streams and activates the capability registry row at startup (`IdempotencySchemaStream`, skipped
@@ -79,8 +79,8 @@ Everything that only makes sense with a relational store therefore lives here an
module: migration startup sequencing, resolved datasource/version validation, OSIV/DDL/pool/TLS/vendor
safety, the sanitized management endpoint/report (`startup`), the metered multi-instance lock
(`lock`), the readiness `db` contribution and the shipped settings
(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay stays in
app-bootstrap because a driven adapter must not construct or call a use case. The leaf must have
(`config/module-defaults/persistence-jpa.yml`). Use-case assembly does not: the outbox relay is
`composition:outbox-relay` because a driven adapter must not construct or call a use case. The leaf must have
zero imports from `dev.caskeleton.bootstrap`; startup failures go through `adapter:outbound:support`
(`support.startup`), and new composition helpers stay package-private so `verifyJpaApiSurface` does
not grow by wiring accident.
@@ -126,7 +126,10 @@ nobody tested.
- Spring Data repositories.
- Persistence mappers.
- Repository adapter implementations.
- Outbox transport-only compatibility: raw `NewOutboxEvent` append belongs only to `LegacyOutboxAppendPort`; canonical `OutboxAppendPort` persists `ValidatedIntegrationEvent` exact bytes. Partial canonical metadata must fail closed.
- Outbox append: one model. `OutboxStoreAdapter` implements `OutboxAppendPort` and persists a
`ValidatedIntegrationEvent`'s exact envelope bytes and hashes; a claim restores the same event
from them. A row without complete canonical metadata is unreadable and goes to DEAD, never
published by guess. `V19` refuses unpublished pre-canonical rows.
- Outbox relay fencing: `claimBatch` records the claiming relay (`lease_owner`) and increments
`lease_token` under the claim's row lock (`V17`); `markPublished`/`markFailed`/`markDead` are one
conditional UPDATE on `event_id` + `IN_FLIGHT` + owner + token and return `APPLIED`/`STALE`. A
@@ -137,7 +140,7 @@ nobody tested.
- Audit-metadata base + actor seam (`audit/AuditableEntity`, `audit/AuditContextPort`,
`audit/DomainContextAuditContextPort`) — see "Persistence auditing contract" below.
- Vendor SPI extension points shared by all RDBMS vendors:
- `outbox/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED).
- `outbox/jpa/OutboxClaimRepository` — vendor module implements claim strategy (e.g. FOR UPDATE SKIP LOCKED); the implementations sit beside it in `outbox/postgresql` and `outbox/h2`.
- `failure/SqlStateErrorMapping` — vendor module contributes vendor-specific SQLState rows.
## Vendor selection
@@ -150,6 +153,11 @@ two SPI beans (outbox claim, SQLState mapping):
| PostgreSQL | `.postgresql` | `ca-skeleton.persistence.vendor=postgresql` (also the default) | Flyway, `db/migration/postgresql` |
| H2 | `.h2` | `ca-skeleton.persistence.vendor=h2` | Hibernate `ddl-auto`, entities only |
The outbox and idempotency features keep their pieces together, by feature and then by vendor:
`outbox/{jpa,postgresql,h2}` and `idempotency/{jpa,postgresql}`. The vendor configurations above still
decide which claim repository is registered. None of those feature classes imports a driver type, so
`PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL` still holds with them outside `.postgresql`.
`config/PersistenceVendorSettings` binds the selector to an enum, so an unknown value fails at
startup instead of loading neither composition and surfacing as a missing `OutboxClaimRepository`.
The profiles state the choice: `application-local.yml`, `application-dev.yml` and
+16 -16
View File
@@ -61,7 +61,7 @@ sample-portfolio가 제공).
| 스위치·vendor | `APP_PERSISTENCE_JPA_ENABLED`(기본 true), `APP_PERSISTENCE_VENDOR`(`postgresql`\|`h2`), `APP_FLYWAY_ENABLED`, `APP_MIGRATION_ON_STARTUP` |
| 풀 | `APP_DATASOURCE_POOL_MAX_SIZE`, `APP_DATASOURCE_POOL_MIN_IDLE`, `APP_DATASOURCE_CONNECTION_TIMEOUT`, `APP_DATASOURCE_POOL_IDLE_TIMEOUT`, `APP_DATASOURCE_POOL_MAX_LIFETIME` |
| JPA | `APP_DATASOURCE_DDL_AUTO`, `APP_DATASOURCE_SHOW_SQL`, `APP_DATASOURCE_FORMAT_SQL`, `APP_DATASOURCE_OPEN_IN_VIEW`, `APP_JPA_HIBERNATE_*` |
| 선택 기능 | `APP_OUTBOX_ENABLED`, `APP_OUTBOX_RELAY_ENABLED`, `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED`, `APP_MULTI_INSTANCE_ENABLED`(합성 루트 소유, 락 provider 선택), `APP_IDEMPOTENCY_PROVIDER=postgresql`, `APP_REALTIME_REPLAY_ENABLED`, `APP_REALTIME_REPLAY_RETENTION` |
| 선택 기능 | `APP_OUTBOX_ENABLED`, `APP_OUTBOX_RELAY_ENABLED`, `APP_MULTI_INSTANCE_ENABLED`(합성 루트 소유, 락 provider 선택), `APP_IDEMPOTENCY_PROVIDER=postgresql`, `APP_REALTIME_REPLAY_ENABLED`, `APP_REALTIME_REPLAY_RETENTION` |
## 라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출
@@ -223,18 +223,19 @@ failure translation contract 다. 여기서는 SPI 구조와 fallback 근거만
## outbox — `OutboxStoreAdapter` 외
스키마는 Flyway(`V3__outbox_event.sql`)가 소유하고, MSG-015 transport-only cutover를 위한
`V13__outbox_canonical_transport_compatibility.sql`이 기존 row를 깨지 않으면서 canonical metadata와
exact `BYTEA envelope_bytes`를 additive하게 확장한다.
스키마는 Flyway(`V3__outbox_event.sql`)가 소유하고, `V13__outbox_canonical_transport_compatibility.sql`이
canonical metadata와 exact `BYTEA envelope_bytes`를 더했다. append 모델은 canonical 하나다(2026-09-28,
소유자 결정 7): `OutboxStoreAdapter`가 `OutboxAppendPort`(`ValidatedIntegrationEvent`)와
`OutboxStorePort`를 함께 구현하고, `ca-skeleton.outbox.enabled=true`일 때만 존재한다. row는 validated
event의 exact envelope bytes와 hash를 저장하고, claim은 그 bytes로 같은 event를 복원한다
(`ClaimedOutboxEvent`). `event_type`·`aggregate_id`·`correlation_id`는 claim gate와 metrics query를
위해 contract id·aggregate id·correlation id를 한 번 더 적는다.
append 경계도 명시적으로 분리된다. `LegacyOutboxAppendPort`는 기존 `NewOutboxEvent` compatibility
producer 전용이고, `OutboxAppendPort`는 `ValidatedIntegrationEvent`만 받는다.
`CanonicalOutboxAppendAdapter`는 `ca-skeleton.outbox.enabled=true`와
`canonical-transport-enabled=true`가 모두 만족될 때만 존재하며 exact bytes를 저장한다. legacy 필수
컬럼에는 rollback window용 UTF-8 compatibility projection을 같이 기록한다.
claim 시 canonical column이 전부 null이면 legacy `OutboxEvent`, 전부 존재하면
`CanonicalClaimedOutboxEvent`로 매핑한다. 일부만 존재하는 row는 legacy로 강등하지 않고 fail-closed한다.
`V19__outbox_event_canonical_only.sql`은 pre-canonical row가 더 없다는 것을 DB에 적는다: envelope 없는
미발행 row가 남아 있으면 migration이 실패하고(이전 릴리스로 relay를 비우거나 손으로 정리한 뒤
다시 적용한다), 이후로는 `PUBLISHED`가 아닌 row에 canonical metadata가 반드시 있다
(`ck_outbox_event_canonical_unless_published`). pre-canonical `payload`·`idempotency_key` 컬럼은
nullable로 남고 아무것도 쓰거나 읽지 않는다 — 이전 릴리스로 되돌릴 때를 위해 지우지 않았다.
### 트랜잭션 경계 계약
- **append**: 호출자의 `TransactionPort.inWrite()` 경계 안에서 호출되어야 하며, 내부에서 새
@@ -260,12 +261,11 @@ FIFO gate 의 "같은 aggregate"와 "앞선 row":
이고, 순서는 `(aggregate_sequence, event_index)` 다. 그래서 `occurred_at` 이 같은 이벤트도 한
번에 하나씩 나가고, 다른 tenant·type 의 DEAD row 가 같은 `aggregate_id` 를 막지 않는다.
인덱스는 `V18` 의 `ix_outbox_event_unpublished_aggregate_order`.
- legacy row 가 끼면 예전처럼 `aggregate_id` + `occurred_at <` 로 비교한다(같은 `occurred_at` 의
legacy row 는 함께 claim된다 — `equalTimestampRowsAreClaimedTogetherLegacyFifoLimitationCharacterization`).
- gate 가 비교하는 row 는 전부 canonical 이다: V19 가 envelope 없는 미발행 row 를 거부한다.
읽을 수 없는 row(부분 canonical metadata, compatibility projection 불일치 등)는 claim 에서 DEAD 로
읽을 수 없는 row(envelope 없음, 부분 metadata, 저장된 hash 와 bytes 불일치 등)는 claim 에서 DEAD 로
옮기고 배치에서 뺀다. 예전에는 예외로 claim transaction 전체가 롤백되고 다음 claim 이 같은 row 를
다시 먼저 골라 relay 가 영구히 멈췄다. legacy 로 낮춰 발행하지 않으므로 fail-closed 는 유지된다.
다시 먼저 골라 relay 가 영구히 멈췄다. 추측해서 발행하지 않으므로 fail-closed 는 유지된다.
eligible row(I3/I4/I6):
- `PENDING` — `next_attempt_at <= now`(insert 시 즉시 eligible)
@@ -153,9 +153,9 @@ def readinessLanes = [
postgresqlAggregateIntegrationTest : ['PostgreSqlAggregateIntegrationTest'],
postgresqlQueryIntegrationTest : ['PostgreSqlQueryIntegrationTest'],
postgresqlIdempotencyIntegrationTest : ['PostgreSqlIdempotencyIntegrationTest'],
postgresqlLegacyOutboxAppendTransactionalIntegrationTest: ['PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest'],
postgresqlLegacyOutboxConcurrentRelayIntegrationTest : ['PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest'],
postgresqlLegacyOutboxRowLifecycleIntegrationTest : ['PostgreSqlLegacyOutboxRowLifecycleIntegrationTest'],
postgresqlOutboxAppendTransactionalIntegrationTest : ['PostgreSqlOutboxAppendTransactionalIntegrationTest'],
postgresqlOutboxConcurrentRelayIntegrationTest : ['PostgreSqlOutboxConcurrentRelayIntegrationTest'],
postgresqlOutboxRowLifecycleIntegrationTest : ['PostgreSqlOutboxRowLifecycleIntegrationTest'],
postgresqlFileserverMigrationIntegrationTest : ['PostgreSqlFileserverMigrationIntegrationTest'],
postgresqlFileserverMetadataIntegrationTest : ['PostgreSqlFileserverMetadataStoreIntegrationTest'],
postgresqlFileserverReclamationIntegrationTest : ['PostgreSqlFileserverReclamationIntegrationTest'],
@@ -1,7 +1,7 @@
package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream;
import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore;
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream;
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore;
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@@ -3,7 +3,8 @@ package dev.caskeleton.adapter.outbound.persistence.h2;
import dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig;
import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings;
import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.h2.H2OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
import jakarta.persistence.EntityManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa;
import java.time.Clock;
import org.slf4j.Logger;
@@ -1,6 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa;
import dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity;
import dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity.IdempotencyRecordEntity;
import java.time.Instant;
import java.util.UUID;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency.entity;
package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import java.util.Objects;
import javax.sql.DataSource;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import dev.caskeleton.application.idempotency.IdempotencyClaimRequest;
import java.util.Objects;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import dev.caskeleton.application.idempotency.IdempotencyState;
import java.time.Instant;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import dev.caskeleton.application.idempotency.IdempotencyState;
import java.sql.ResultSet;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import java.util.Objects;
import javax.sql.DataSource;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import dev.caskeleton.application.idempotency.IdempotencyOwner;
import java.time.Duration;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt;
import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome;
@@ -1,105 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Canonical append path for the transport-only outbox cutover.
*
* <p>The existing {@code outbox_event} row remains the durable authority. Canonical metadata and
* exact envelope bytes are stored additively while legacy required columns receive a reversible
* compatibility projection. This adapter never opens its own transaction.
*/
@Repository
@ConditionalOnProperty(
prefix = "ca-skeleton.outbox",
name = {"enabled", "canonical-transport-enabled"},
havingValue = "true")
final class CanonicalOutboxAppendAdapter implements OutboxAppendPort {
private final OutboxEventJpaRepository repository;
CanonicalOutboxAppendAdapter(OutboxEventJpaRepository repository) {
this.repository = Objects.requireNonNull(repository, "repository must not be null");
}
@Override
public void append(ValidatedIntegrationEvent event) {
// Outside a caller transaction the row commits on its own, apart from the business write it
// announces — the dual write the outbox exists to prevent.
if (!TransactionSynchronizationManager.isActualTransactionActive()) {
throw new IllegalStateException("outbox append requires an active caller transaction");
}
Objects.requireNonNull(event, "event must not be null");
byte[] envelopeBytes = event.envelopeBytes();
String compatibilityPayload = strictUtf8(envelopeBytes);
OutboxEventEntity entity = new OutboxEventEntity();
// Legacy compatibility projection retained while the v1 relay owns the row lifecycle.
entity.setEventId(event.eventId().value());
entity.setAggregateId(event.aggregate().aggregateId());
entity.setEventType(event.contractId().value());
entity.setPayload(compatibilityPayload);
entity.setOccurredAt(event.occurredAt());
entity.setStatus(OutboxEventStatus.PENDING.name());
entity.setAttemptCount(0);
entity.setNextAttemptAt(event.occurredAt());
entity.setCorrelationId(event.correlationId());
entity.setIdempotencyKey(event.eventId().value());
// Canonical authority for the new platform transport branch.
entity.setContractId(event.contractId().value());
entity.setEnvelopeVersion(event.envelopeVersion());
entity.setPayloadVersion(event.payloadVersion());
entity.setLogicalDestination(event.logicalDestinationId().value());
entity.setTenantScope(event.aggregate().tenantScope());
entity.setAggregateType(event.aggregate().aggregateType());
entity.setAggregateSequence(event.order().sequence());
entity.setEventIndex(event.order().eventIndex());
entity.setPartitionKey(event.partitionKeyText());
entity.setEnvelopeBytes(envelopeBytes);
entity.setContentType(event.contentType());
entity.setSchemaSetHash(event.schemaSetHash().toString());
entity.setEnvelopeSha256(event.envelopeSha256().toString());
entity.setEnvelopeSchemaHash(event.envelopeSchemaHash().toString());
entity.setPayloadSchemaHash(event.payloadSchemaHash().toString());
entity.setContractCatalogRevision(event.contractCatalogRevision());
entity.setDestinationBindingRevision(event.destinationBindingRevision());
entity.setCausationId(event.causationId().orElse(null));
repository.save(entity);
}
private static String strictUtf8(byte[] bytes) {
try {
String decoded =
StandardCharsets.UTF_8
.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString();
if (!Arrays.equals(decoded.getBytes(StandardCharsets.UTF_8), bytes)) {
throw new IllegalArgumentException(
"canonical envelope must round-trip as exact UTF-8 for the legacy compatibility projection");
}
return decoded;
} catch (CharacterCodingException exception) {
throw new IllegalArgumentException(
"canonical envelope must be valid UTF-8 for the legacy compatibility projection",
exception);
}
}
}
@@ -1,7 +1,7 @@
package dev.caskeleton.adapter.outbound.persistence.h2;
package dev.caskeleton.adapter.outbound.persistence.outbox.h2;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.util.List;
@@ -28,17 +28,13 @@ public final class H2OutboxClaimRepository implements OutboxClaimRepository {
AND o.status IN ('PENDING', 'FAILED', 'IN_FLIGHT')
AND NOT EXISTS (
SELECT 1 FROM outbox_event p
WHERE p.aggregate_id = o.aggregate_id
AND p.status <> 'PUBLISHED'
AND CASE
WHEN o.contract_id IS NOT NULL AND p.contract_id IS NOT NULL THEN
p.tenant_scope = o.tenant_scope
AND p.aggregate_type = o.aggregate_type
AND (p.aggregate_sequence < o.aggregate_sequence
OR (p.aggregate_sequence = o.aggregate_sequence
AND p.event_index < o.event_index))
ELSE p.occurred_at < o.occurred_at
END
WHERE p.aggregate_id = o.aggregate_id
AND p.tenant_scope = o.tenant_scope
AND p.aggregate_type = o.aggregate_type
AND p.status <> 'PUBLISHED'
AND (p.aggregate_sequence < o.aggregate_sequence
OR (p.aggregate_sequence = o.aggregate_sequence
AND p.event_index < o.event_index))
)
ORDER BY o.occurred_at ASC, o.aggregate_sequence ASC, o.event_index ASC
LIMIT :limit
@@ -1,6 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import java.time.Instant;
import java.util.List;
@@ -1,6 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import java.time.Instant;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import java.time.Clock;
import java.time.Duration;
@@ -31,8 +31,8 @@ public class OutboxReaper {
private final Clock clock;
private final Duration retention;
// @Value is acceptable for this single reaper-local value; canonical settings live in
// app-bootstrap OutboxSettings / application.yml.
// @Value is acceptable for this single reaper-local value; the settings are declared and
// validated once, in composition:outbox-relay OutboxSettings.
public OutboxReaper(
OutboxEventJpaRepository repository,
Clock clock,
@@ -1,6 +1,6 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
@@ -8,18 +8,12 @@ import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent;
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.outbox.OutboxCompletion;
import dev.caskeleton.application.outbox.OutboxEvent;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
import dev.caskeleton.application.outbox.OutboxStorePort;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
@@ -29,6 +23,7 @@ import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,15 +32,20 @@ import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* JPA-backed {@link LegacyOutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the
* claim/mark operations run inside the caller's {@code TransactionPort.inWrite()} boundary and
* declare no {@code @Transactional} of their own; {@link #claimBatch} delegates the vendor claim to
* {@link OutboxClaimRepository}. See README "outbox" for the append/claim/no-@Transactional
* contracts.
* JPA-backed {@link OutboxAppendPort} + {@link OutboxStorePort}. {@link #append} and the claim/mark
* operations run inside the caller's {@code TransactionPort.inWrite()} boundary and declare no
* {@code @Transactional} of their own; {@link #claimBatch} delegates the vendor claim to {@link
* OutboxClaimRepository}. See README "outbox" for the append/claim/no-@Transactional contracts.
*
* <p>A row stores the exact envelope bytes and hashes of the {@link ValidatedIntegrationEvent} it
* was appended with, and a claim restores that event from them, so the relay publishes the bytes
* that were validated. The {@code event_type}, {@code aggregate_id} and {@code correlation_id}
* columns repeat the contract id, aggregate id and correlation id for the claim gate and the
* metrics queries.
*/
@Repository
@ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true")
public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePort {
public class OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort {
private static final Logger log = LoggerFactory.getLogger(OutboxStoreAdapter.class);
@@ -59,20 +59,40 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo
}
@Override
public void append(NewOutboxEvent event) {
public void append(ValidatedIntegrationEvent event) {
// Outside a caller transaction the row commits on its own, apart from the business write it
// announces — the dual write the outbox exists to prevent.
requireTransaction("append");
Objects.requireNonNull(event, "event must not be null");
OutboxEventEntity entity = new OutboxEventEntity();
entity.setEventId(event.eventId());
entity.setAggregateId(event.aggregateId());
entity.setEventType(event.eventType());
entity.setPayload(event.payload());
entity.setEventId(event.eventId().value());
entity.setAggregateId(event.aggregate().aggregateId());
entity.setEventType(event.contractId().value());
entity.setOccurredAt(event.occurredAt());
entity.setStatus(OutboxEventStatus.PENDING.name());
entity.setAttemptCount(0);
// PENDING: nextAttemptAt = occurredAt so the relay can claim immediately.
entity.setNextAttemptAt(event.occurredAt());
entity.setCorrelationId(event.correlationId());
entity.setIdempotencyKey(event.idempotencyKey());
entity.setContractId(event.contractId().value());
entity.setEnvelopeVersion(event.envelopeVersion());
entity.setPayloadVersion(event.payloadVersion());
entity.setLogicalDestination(event.logicalDestinationId().value());
entity.setTenantScope(event.aggregate().tenantScope());
entity.setAggregateType(event.aggregate().aggregateType());
entity.setAggregateSequence(event.order().sequence());
entity.setEventIndex(event.order().eventIndex());
entity.setPartitionKey(event.partitionKeyText());
entity.setEnvelopeBytes(event.envelopeBytes());
entity.setContentType(event.contentType());
entity.setSchemaSetHash(event.schemaSetHash().toString());
entity.setEnvelopeSha256(event.envelopeSha256().toString());
entity.setEnvelopeSchemaHash(event.envelopeSchemaHash().toString());
entity.setPayloadSchemaHash(event.payloadSchemaHash().toString());
entity.setContractCatalogRevision(event.contractCatalogRevision());
entity.setDestinationBindingRevision(event.destinationBindingRevision());
entity.setCausationId(event.causationId().orElse(null));
repository.save(entity);
}
@@ -82,8 +102,8 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo
*
* <p>A row that cannot be read as an event is moved to DEAD and left out of the batch. Throwing
* instead rolled the whole claim back, and the next claim selected the same row first again, so
* one bad row stopped the relay for good. DEAD is fail-closed: the row is never published or
* downgraded to a legacy claim, and it waits for the DEAD-row runbook like any other.
* one bad row stopped the relay for good. DEAD is fail-closed: the row is never published, and it
* waits for the DEAD-row runbook like any other.
*/
@Override
public List<OutboxLease> claimBatch(
@@ -176,40 +196,19 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo
return result;
}
/**
* Restores the appended event. A row without its envelope — written by the pre-canonical
* generation, or damaged — is unreadable, and so is one whose stored hash is not the hash of its
* bytes: {@link ValidatedIntegrationEvent} recomputes it, so a row cannot vouch for itself.
*/
private static ClaimedOutboxEvent toClaimedOutboxEvent(OutboxEventEntity entity) {
if (!hasAnyCanonicalMetadata(entity)) {
return toLegacyOutboxEvent(entity);
}
if (!hasCompleteCanonicalMetadata(entity)) {
throw new IllegalStateException(
"outbox row contains partial canonical metadata for eventId=" + entity.getEventId());
"outbox row eventId="
+ entity.getEventId()
+ " carries no complete canonical envelope; the pre-canonical relay that read such"
+ " rows is gone");
}
return toCanonicalOutboxEvent(entity);
}
private static OutboxEvent toLegacyOutboxEvent(OutboxEventEntity entity) {
return new OutboxEvent(
entity.getEventId(),
entity.getEventType(),
entity.getAggregateId(),
entity.getPayload(),
entity.getOccurredAt(),
entity.getCorrelationId(),
entity.getIdempotencyKey(),
OutboxEventStatus.valueOf(entity.getStatus()),
entity.getAttemptCount());
}
private static CanonicalClaimedOutboxEvent toCanonicalOutboxEvent(OutboxEventEntity entity) {
byte[] envelopeBytes = entity.getEnvelopeBytes();
String compatibilityPayload = strictUtf8(envelopeBytes, entity.getEventId());
if (!entity.getEventType().equals(entity.getContractId())
|| !entity.getIdempotencyKey().equals(entity.getEventId())
|| !entity.getPayload().equals(compatibilityPayload)) {
throw new IllegalStateException(
"canonical outbox compatibility projection mismatch for eventId=" + entity.getEventId());
}
try {
ValidatedIntegrationEvent event =
new ValidatedIntegrationEvent(
@@ -226,7 +225,7 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo
Optional.ofNullable(entity.getCausationId()),
entity.getPartitionKey(),
entity.getPartitionKey().getBytes(StandardCharsets.US_ASCII),
envelopeBytes,
entity.getEnvelopeBytes(),
entity.getContentType(),
digest(entity.getSchemaSetHash(), "schema_set_hash", entity.getEventId()),
digest(entity.getEnvelopeSha256(), "envelope_sha256", entity.getEventId()),
@@ -234,7 +233,7 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo
digest(entity.getPayloadSchemaHash(), "payload_schema_hash", entity.getEventId()),
entity.getContractCatalogRevision(),
entity.getDestinationBindingRevision());
return new CanonicalClaimedOutboxEvent(
return new ClaimedOutboxEvent(
event, OutboxEventStatus.valueOf(entity.getStatus()), entity.getAttemptCount());
} catch (IllegalArgumentException exception) {
throw new IllegalStateException(
@@ -242,27 +241,6 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo
}
}
private static boolean hasAnyCanonicalMetadata(OutboxEventEntity entity) {
return entity.getContractId() != null
|| entity.getEnvelopeVersion() != null
|| entity.getPayloadVersion() != null
|| entity.getLogicalDestination() != null
|| entity.getTenantScope() != null
|| entity.getAggregateType() != null
|| entity.getAggregateSequence() != null
|| entity.getEventIndex() != null
|| entity.getPartitionKey() != null
|| entity.getEnvelopeBytes() != null
|| entity.getContentType() != null
|| entity.getSchemaSetHash() != null
|| entity.getEnvelopeSha256() != null
|| entity.getEnvelopeSchemaHash() != null
|| entity.getPayloadSchemaHash() != null
|| entity.getContractCatalogRevision() != null
|| entity.getDestinationBindingRevision() != null
|| entity.getCausationId() != null;
}
private static boolean hasCompleteCanonicalMetadata(OutboxEventEntity entity) {
return entity.getContractId() != null
&& entity.getEnvelopeVersion() != null
@@ -288,21 +266,7 @@ public class OutboxStoreAdapter implements LegacyOutboxAppendPort, OutboxStorePo
return new Sha256(HexFormat.of().parseHex(hex));
} catch (IllegalArgumentException exception) {
throw new IllegalArgumentException(
"invalid " + field + " for canonical outbox eventId=" + eventId, exception);
}
}
private static String strictUtf8(byte[] bytes, String eventId) {
try {
return StandardCharsets.UTF_8
.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString();
} catch (CharacterCodingException exception) {
throw new IllegalStateException(
"canonical outbox envelope is not valid UTF-8 for eventId=" + eventId, exception);
"invalid " + field + " for outbox eventId=" + eventId, exception);
}
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.outbox.entity;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
@@ -8,16 +8,15 @@ import jakarta.persistence.PostPersist;
import jakarta.persistence.Table;
import jakarta.persistence.Transient;
import java.time.Instant;
import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
import org.springframework.data.domain.Persistable;
/**
* JPA row for the {@code outbox_event} table; schema owned by Flyway ({@code V3__outbox_event.sql}
* + additive canonical metadata in {@code V13__outbox_canonical_transport_compatibility.sql} + the
* relay lease in {@code V17__outbox_event_lease_fencing.sql}). Does not extend {@code
* AuditableEntity} (infra record, not a domain aggregate) and exposes mutating setters on purpose
* (relay transitions state in-place).
* relay lease in {@code V17__outbox_event_lease_fencing.sql} + the canonical-only rule in {@code
* V19__outbox_event_canonical_only.sql}). Does not extend {@code AuditableEntity} (infra record,
* not a domain aggregate) and exposes mutating setters on purpose (relay transitions state
* in-place).
*
* <p>{@link Persistable} so that {@code save} of a new row is always an insert. With an assigned
* identifier and no version, Spring Data treats every entity as existing and merges it, and a
@@ -41,10 +40,6 @@ public class OutboxEventEntity implements Persistable<String> {
@Column(name = "event_type", nullable = false, length = 256, updatable = false)
private String eventType;
@JdbcTypeCode(SqlTypes.LONGVARCHAR)
@Column(name = "payload", nullable = false, updatable = false)
private String payload;
@Column(name = "occurred_at", nullable = false, updatable = false)
private Instant occurredAt;
@@ -70,10 +65,9 @@ public class OutboxEventEntity implements Persistable<String> {
@Column(name = "correlation_id", nullable = false, length = 128, updatable = false)
private String correlationId;
@Column(name = "idempotency_key", nullable = false, length = 256, updatable = false)
private String idempotencyKey;
// V13 canonical transport-only compatibility columns. Null as a set means an R0 legacy row.
// The canonical envelope (V13). A claimable row always has all of them (V19); the pre-canonical
// payload and idempotency_key columns stay in the table, unmapped and nullable, for rows written
// before and read by nothing now.
@Column(name = "contract_id", length = 160, updatable = false)
private String contractId;
@@ -171,14 +165,6 @@ public class OutboxEventEntity implements Persistable<String> {
this.eventType = eventType;
}
public String getPayload() {
return payload;
}
public void setPayload(String payload) {
this.payload = payload;
}
public Instant getOccurredAt() {
return occurredAt;
}
@@ -235,14 +221,6 @@ public class OutboxEventEntity implements Persistable<String> {
this.correlationId = correlationId;
}
public String getIdempotencyKey() {
return idempotencyKey;
}
public void setIdempotencyKey(String idempotencyKey) {
this.idempotencyKey = idempotencyKey;
}
public String getContractId() {
return contractId;
}
@@ -1,7 +1,7 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql;
package dev.caskeleton.adapter.outbound.persistence.outbox.postgresql;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import jakarta.persistence.EntityManager;
import java.time.Instant;
import java.util.List;
@@ -14,8 +14,8 @@ import java.util.List;
* rows are the same aggregate only with the same {@code (tenant_scope, aggregate_type,
* aggregate_id)}, and earlier means a lower {@code (aggregate_sequence, event_index)} — so events
* that share an {@code occurred_at} are still released one at a time, and a DEAD row of another
* tenant or type does not block this one. Any pair involving a legacy row keeps the {@code
* occurred_at} comparison it always had.
* tenant or type does not block this one. Every row the gate compares is canonical: V19 refuses an
* unpublished row without the canonical envelope.
*/
public class PostgreSqlOutboxClaimRepository implements OutboxClaimRepository {
@@ -26,17 +26,13 @@ public class PostgreSqlOutboxClaimRepository implements OutboxClaimRepository {
AND o.status IN ('PENDING', 'FAILED', 'IN_FLIGHT')
AND NOT EXISTS (
SELECT 1 FROM outbox_event p
WHERE p.aggregate_id = o.aggregate_id
AND p.status <> 'PUBLISHED'
AND CASE
WHEN o.contract_id IS NOT NULL AND p.contract_id IS NOT NULL THEN
p.tenant_scope = o.tenant_scope
AND p.aggregate_type = o.aggregate_type
AND (p.aggregate_sequence < o.aggregate_sequence
OR (p.aggregate_sequence = o.aggregate_sequence
AND p.event_index < o.event_index))
ELSE p.occurred_at < o.occurred_at
END
WHERE p.aggregate_id = o.aggregate_id
AND p.tenant_scope = o.tenant_scope
AND p.aggregate_type = o.aggregate_type
AND p.status <> 'PUBLISHED'
AND (p.aggregate_sequence < o.aggregate_sequence
OR (p.aggregate_sequence = o.aggregate_sequence
AND p.event_index < o.event_index))
)
ORDER BY o.occurred_at ASC, o.aggregate_sequence ASC, o.event_index ASC
LIMIT :limit
@@ -3,7 +3,8 @@ package dev.caskeleton.adapter.outbound.persistence.postgresql;
import dev.caskeleton.adapter.outbound.persistence.config.PersistenceJpaConfig;
import dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings;
import dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository;
import jakarta.persistence.EntityManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.flyway.autoconfigure.FlywayConfigurationCustomizer;
@@ -175,8 +175,9 @@ ca-skeleton:
enabled: ${APP_REALTIME_REPLAY_ENABLED:false}
retention: ${APP_REALTIME_REPLAY_RETENTION:1h}
outbox:
# feature-domain-event-outbox-contract I11 — all six values are literal defaults;
# NO env placeholders (spec: 신규 env key 없음). Bound into OutboxProperties.
# feature-domain-event-outbox-contract I11 — the tuning values are literal defaults;
# NO env placeholders (spec: 신규 env key 없음). Declared, validated and strictly bound by
# composition:outbox-relay OutboxSettings: an unknown key here fails startup.
# true | false — enable/disable the relay scheduler (OutboxRelayScheduler).
# The scheduler starts only when a publishing capability contributes an
# OutboxMessagePublishPort, so an environment without one keeps its PENDING rows instead of
@@ -187,9 +188,6 @@ ca-skeleton:
# port that a database-less deployment does not have.
enabled: ${APP_OUTBOX_ENABLED:false}
relay-enabled: ${APP_OUTBOX_RELAY_ENABLED:false}
# Transport-only MSG-015 cutover gate. It does not start a second relay.
# When true, startup also requires the canonical IntegrationEventPublishPort.
canonical-transport-enabled: ${APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED:false}
# ISO-8601 duration — how often the relay polls for pending rows
poll-interval: PT5S
# integer >= 1 — maximum rows claimed per relay cycle
@@ -0,0 +1,36 @@
-- The outbox has one append model now: the canonical ValidatedIntegrationEvent (envelope bytes plus
-- the V13 metadata). The pre-canonical relay that published rows from the free-text payload column
-- is gone, so a row without the envelope can no longer be delivered by anything.
--
-- 1. Refuse to migrate while such a row still waits. Dead-lettering it here would drop an event an
-- older release could still publish, and letting it through would leave it blocking its
-- aggregate's FIFO queue for ever. Drain the relay with the previous release first, or resolve
-- the rows by hand (see the outbox DEAD-row runbook), then run this migration again.
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM outbox_event WHERE contract_id IS NULL AND status <> 'PUBLISHED'
) THEN
RAISE EXCEPTION
'outbox_event still holds unpublished rows without a canonical envelope; drain them with '
'the previous release (or resolve them by hand) before applying V19';
END IF;
END
$$;
-- 2. The canonical append writes neither pre-canonical column. They stay, nullable, so a rollback
-- to the previous release still finds them; nothing reads them any more.
ALTER TABLE outbox_event
ALTER COLUMN payload DROP NOT NULL,
ALTER COLUMN idempotency_key DROP NOT NULL;
-- 3. From here on every row that can still be claimed carries the envelope. PUBLISHED rows written
-- before this migration are exempt until the reaper deletes them.
ALTER TABLE outbox_event
ADD CONSTRAINT ck_outbox_event_canonical_unless_published
CHECK (contract_id IS NOT NULL OR status = 'PUBLISHED');
COMMENT ON COLUMN outbox_event.payload IS
'Pre-canonical payload text. Not written since V19; the envelope is envelope_bytes.';
COMMENT ON COLUMN outbox_event.idempotency_key IS
'Pre-canonical dedup key. Not written since V19; consumers deduplicate on event_id.';
@@ -4,13 +4,15 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.platform.JpaPlatformContractSupport;
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort;
import dev.caskeleton.adapter.outbound.support.messaging.JsonIntegrationEventEncoder;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.operation.DurableOperationId;
import dev.caskeleton.application.operation.DurableOperationSubmittedContract;
import dev.caskeleton.application.operation.OperationAcceptance;
import dev.caskeleton.application.operation.OperationCommand;
import dev.caskeleton.application.operation.SubmitDurableOperationUseCase;
@@ -91,6 +93,19 @@ class DurableOperationSubmissionOutboxIntegrationTest {
execute("TRUNCATE durable_operation, outbox_event");
}
@Test
void aSubmissionStoresTheEncodedSubmittedEventAsACanonicalRow() throws SQLException {
// given
SubmitDurableOperationUseCase useCase = context.getBean(SubmitDurableOperationUseCase.class);
// when
useCase.handle(command());
// then
assertThat(queryStrings("SELECT contract_id || '|' || aggregate_id FROM outbox_event"))
.containsExactly("durable-operation.submitted|op-1");
}
@Test
void retryUnderTheSameOperationIdLeavesThePublishedOutboxRowAlone() throws SQLException {
// given
@@ -135,14 +150,16 @@ class DurableOperationSubmissionOutboxIntegrationTest {
null,
new RequestFingerprint("a".repeat(64)),
"{\"range\":\"2026-08\"}",
OperationCommand.SUBMITTED_EVENT_TYPE,
Duration.ofDays(1));
}
private static List<String> outboxStatuses() throws SQLException {
return queryStrings("SELECT status FROM outbox_event ORDER BY event_id");
}
private static List<String> queryStrings(String sql) throws SQLException {
try (Connection connection = support.connection();
PreparedStatement statement =
connection.prepareStatement("SELECT status FROM outbox_event ORDER BY event_id");
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rows = statement.executeQuery()) {
List<String> statuses = new ArrayList<>();
while (rows.next()) {
@@ -198,6 +215,7 @@ class DurableOperationSubmissionOutboxIntegrationTest {
new DurableOperationStoreAdapter(operations),
// The claim is never exercised here; submission only appends.
new OutboxStoreAdapter(outbox, (now, limit) -> List.of()),
new JsonIntegrationEventEncoder(List.of(new DurableOperationSubmittedContract())),
transactions,
Clock.fixed(NOW, ZoneOffset.UTC));
}
@@ -1,9 +1,9 @@
package dev.caskeleton.adapter.outbound.persistence.readiness;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter;
import dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter;
import dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository;
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort;
import dev.caskeleton.application.outbox.OutboxBackoffPolicy;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
@@ -29,19 +29,19 @@ import org.springframework.orm.jpa.SharedEntityManagerCreator;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
/**
* Shared real-PostgreSQL + Spring context support for legacy outbox integration tests
* Shared real-PostgreSQL + Spring context support for outbox integration tests
* (feature-domain-event-outbox-contract Task E).
*
* <p>Does NOT boot the full {@code CaSkeletonApplication}. Builds a minimal {@link
* AnnotationConfigApplicationContext} with only the JPA / outbox persistence beans needed for the
* outbox integration tests.
*/
final class LegacyOutboxIntegrationSupport {
final class OutboxIntegrationSupport {
static final int BATCH_SIZE_CONTRACT = 50;
static final Duration IN_FLIGHT_TIMEOUT = Duration.ofSeconds(30);
private LegacyOutboxIntegrationSupport() {}
private OutboxIntegrationSupport() {}
/**
* Runs Flyway migrations against the given DataSource. All three migrations (V1 idempotency, V2
@@ -84,8 +84,7 @@ final class LegacyOutboxIntegrationSupport {
.getPropertySources()
.addFirst(
new MapPropertySource(
"legacy-outbox-integration",
java.util.Map.of("ca-skeleton.outbox.enabled", "true")));
"outbox-integration", java.util.Map.of("ca-skeleton.outbox.enabled", "true")));
// Register DataSource — no destroy (caller owns lifecycle).
ctx.registerBean(
@@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore;
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore;
import dev.caskeleton.application.idempotency.IdempotencyClaimAttempt;
import dev.caskeleton.application.idempotency.IdempotencyClaimOutcome;
import dev.caskeleton.application.idempotency.IdempotencyClaimRequest;
@@ -1,8 +1,8 @@
package dev.caskeleton.adapter.outbound.persistence.readiness;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.testkit.LegacyOutboxAppendContract;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.outbox.testkit.OutboxAppendContract;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
import java.time.Instant;
@@ -20,7 +20,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
* <p>Proves the no-dual-write guarantee (D2): if the business transaction rolls back, the outbox
* row vanishes with it — there is no separate out-of-band insert.
*/
class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest {
class PostgreSqlOutboxAppendTransactionalIntegrationTest {
private static PostgreSqlReadinessSupport postgres;
private static DataSource sharedDataSource;
@@ -29,7 +29,7 @@ class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest {
static void setup() {
postgres = PostgreSqlReadinessSupport.start();
sharedDataSource = postgres.dataSource();
LegacyOutboxIntegrationSupport.migrate(sharedDataSource);
OutboxIntegrationSupport.migrate(sharedDataSource);
}
@AfterAll
@@ -44,13 +44,13 @@ class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest {
Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxEventJpaRepository repo = ctx.getBean(OutboxEventJpaRepository.class);
LegacyOutboxAppendContract.verifyRollbackRemovesEvent(
OutboxAppendContract.verifyRollbackRemovesEvent(
tx, append, eventId -> repo.findById(eventId).isPresent(), clock);
}
}
@@ -60,13 +60,13 @@ class PostgreSqlLegacyOutboxAppendTransactionalIntegrationTest {
Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxEventJpaRepository repo = ctx.getBean(OutboxEventJpaRepository.class);
LegacyOutboxAppendContract.verifyCommitPersistsEvent(
OutboxAppendContract.verifyCommitPersistsEvent(
tx, append, eventId -> repo.findById(eventId).isPresent(), clock);
}
}
@@ -1,10 +1,11 @@
package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
import dev.caskeleton.application.transaction.TransactionPort;
@@ -20,6 +21,8 @@ import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
@@ -27,14 +30,15 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* The claim gate, the claim's handling of unreadable rows, the status gauge query and the reaper,
* against real PostgreSQL through the shipped outbox store.
*
* <p>Canonical rows are written with SQL because the canonical append adapter is internal to its
* package; the columns are the ones that adapter writes.
* <p>Rows are written with SQL so a test can store one the append port would refuse — a damaged
* envelope, a row without one; the columns are the ones the append writes.
*/
@Tag("jpa-contract")
class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
@@ -55,7 +59,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
static void start() {
postgres = PostgreSqlReadinessSupport.start();
dataSource = postgres.dataSource();
LegacyOutboxIntegrationSupport.migrate(dataSource);
OutboxIntegrationSupport.migrate(dataSource);
}
@AfterAll
@@ -70,7 +74,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
jdbc = new JdbcTemplate(dataSource);
jdbc.execute("TRUNCATE outbox_event");
context =
LegacyOutboxIntegrationSupport.buildContext(
OutboxIntegrationSupport.buildContext(
dataSource, event -> {}, Clock.fixed(NOW, ZoneOffset.UTC));
}
@@ -113,9 +117,8 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
void anUnreadableCanonicalRowDoesNotStopTheRestOfTheBatchFromBeingClaimed() {
// given
insertCanonical("unreadable", "tenant-a", "worklog", 1, 0, "PENDING");
jdbc.update(
"UPDATE outbox_event SET payload = 'not the envelope' WHERE event_id = 'unreadable'");
insertLegacy("readable", "PENDING", OCCURRED);
damageEnvelopeHash("unreadable");
insertStandalone("readable", "PENDING");
// when
List<String> claimed = claim();
@@ -128,8 +131,7 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
void anUnreadableCanonicalRowIsMovedToDeadByTheClaim() {
// given
insertCanonical("unreadable", "tenant-a", "worklog", 1, 0, "PENDING");
jdbc.update(
"UPDATE outbox_event SET payload = 'not the envelope' WHERE event_id = 'unreadable'");
damageEnvelopeHash("unreadable");
// when
claim();
@@ -141,8 +143,8 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
@Test
void countByStatusLeavesPublishedRowsUncounted() {
// given
insertLegacy("published", "PUBLISHED", OCCURRED);
insertLegacy("pending", "PENDING", OCCURRED);
insertStandalone("published", "PUBLISHED");
insertStandalone("pending", "PENDING");
// when
Map<OutboxEventStatus, Long> counts = context.getBean(OutboxStoreAdapter.class).countByStatus();
@@ -155,9 +157,9 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
void reaperDeletesOldPublishedRowsOutsideAnyCallerTransaction() {
// given
for (int index = 0; index < 5; index++) {
insertLegacy("published-" + index, "PUBLISHED", OCCURRED);
insertStandalone("published-" + index, "PUBLISHED");
}
insertLegacy("pending", "PENDING", OCCURRED);
insertStandalone("pending", "PENDING");
OutboxReaper reaper =
new OutboxReaper(
context.getBean(OutboxEventJpaRepository.class),
@@ -171,6 +173,62 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
assertThat(List.of(purged, rowCount())).containsExactly(5, 1);
}
@Test
void aRowWithoutTheCanonicalEnvelopeIsRefusedUnlessItIsPublished() {
// when
Throwable thrown = catchThrowable(() -> insertPreCanonical("pre-canonical", "PENDING"));
// then
assertThat(thrown)
.isInstanceOf(DataIntegrityViolationException.class)
.hasMessageContaining("ck_outbox_event_canonical_unless_published");
}
@Test
void aPublishedPreCanonicalRowIsKeptForTheReaper() {
// when
insertPreCanonical("pre-canonical-published", "PUBLISHED");
// then
assertThat(status("pre-canonical-published")).isEqualTo("PUBLISHED");
}
@Test
void theCanonicalOnlyMigrationRefusesADatabaseThatStillHoldsAnUndeliveredPreCanonicalRow() {
// given
String schema = "outbox_v19_guard";
Flyway.configure()
.dataSource(dataSource)
.schemas(schema)
.locations("classpath:db/migration/postgresql")
.target("18")
.load()
.migrate();
jdbc.update(
"INSERT INTO "
+ schema
+ ".outbox_event (event_id, aggregate_id, event_type, payload, occurred_at, status,"
+ " attempt_count, next_attempt_at, correlation_id, idempotency_key)"
+ " VALUES ('waiting', 'agg-1', 'TestEvent', '{}', now(), 'PENDING', 0, now(),"
+ " 'corr-1', 'waiting')");
// when
Throwable thrown =
catchThrowable(
() ->
Flyway.configure()
.dataSource(dataSource)
.schemas(schema)
.locations("classpath:db/migration/postgresql")
.load()
.migrate());
// then
assertThat(thrown)
.isInstanceOf(FlywayException.class)
.hasMessageContaining("unpublished rows without a canonical envelope");
}
private List<String> claim() {
OutboxStoreAdapter store = context.getBean(OutboxStoreAdapter.class);
List<OutboxLease> leases =
@@ -187,7 +245,8 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
long sequence,
int eventIndex,
String status) {
insertCanonical(eventId, tenantScope, aggregateType, sequence, eventIndex, status, OCCURRED);
insertCanonical(
eventId, "worklog-42", tenantScope, aggregateType, sequence, eventIndex, status, OCCURRED);
}
private void insertCanonical(
@@ -198,25 +257,44 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
int eventIndex,
String status,
Instant occurredAt) {
insertCanonical(
eventId,
"worklog-42",
tenantScope,
aggregateType,
sequence,
eventIndex,
status,
occurredAt);
}
private void insertCanonical(
String eventId,
String aggregateId,
String tenantScope,
String aggregateType,
long sequence,
int eventIndex,
String status,
Instant occurredAt) {
jdbc.update(
"""
INSERT INTO outbox_event (
event_id, aggregate_id, event_type, payload, occurred_at, status, attempt_count,
next_attempt_at, correlation_id, idempotency_key,
event_id, aggregate_id, event_type, occurred_at, status, attempt_count,
next_attempt_at, correlation_id,
contract_id, envelope_version, payload_version, logical_destination, tenant_scope,
aggregate_type, aggregate_sequence, event_index, partition_key, envelope_bytes,
content_type, schema_set_hash, envelope_sha256, envelope_schema_hash,
payload_schema_hash, contract_catalog_revision, destination_binding_revision)
VALUES (?, 'worklog-42', 'portfolio.worklog.reserved', ?, ?, ?, 0, ?, 'corr-1', ?,
VALUES (?, ?, 'portfolio.worklog.reserved', ?, ?, 0, ?, 'corr-1',
'portfolio.worklog.reserved', 1, 3, 'portfolio-domain-events', ?, ?, ?, ?, ?, ?,
'application/json', ?, ?, ?, ?, 'catalog-r1', 'binding-r1')
""",
eventId,
ENVELOPE,
aggregateId,
Timestamp.from(occurredAt),
status,
Timestamp.from(occurredAt),
eventId,
tenantScope,
aggregateType,
sequence,
@@ -229,7 +307,19 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
"4".repeat(64));
}
private void insertLegacy(String eventId, String status, Instant occurredAt) {
/** A canonical row that is the only event of its own aggregate. */
private void insertStandalone(String eventId, String status) {
insertCanonical(eventId, "agg-" + eventId, "tenant-a", "worklog", 1, 0, status, OCCURRED);
}
/** The hash no longer matches the bytes, so the claim cannot restore the event. */
private void damageEnvelopeHash(String eventId) {
jdbc.update(
"UPDATE outbox_event SET envelope_sha256 = ? WHERE event_id = ?", "2".repeat(64), eventId);
}
/** A row as the pre-canonical append wrote it: payload text, no envelope. */
private void insertPreCanonical(String eventId, String status) {
jdbc.update(
"""
INSERT INTO outbox_event (
@@ -239,9 +329,9 @@ class PostgreSqlOutboxClaimAndMaintenanceIntegrationTest {
""",
eventId,
"agg-" + eventId,
Timestamp.from(occurredAt),
Timestamp.from(OCCURRED),
status,
Timestamp.from(occurredAt),
Timestamp.from(OCCURRED),
eventId);
}
@@ -2,14 +2,14 @@ package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxRelayResult;
import dev.caskeleton.application.outbox.OutboxStorePort;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
import dev.caskeleton.application.outbox.testkit.OutboxLeaseFencingContract;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
@@ -42,7 +42,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
* ConcurrentHashMap}. Both relay loops run until the store is drained (claimedCount == 0 for both
* instances). Then assert total = 1000, duplicates = 0.
*/
class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingContract {
class PostgreSqlOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFencingContract {
private static PostgreSqlReadinessSupport postgres;
private static DataSource sharedDataSource;
@@ -52,9 +52,9 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe
static void setup() {
postgres = PostgreSqlReadinessSupport.start();
sharedDataSource = postgres.dataSource();
LegacyOutboxIntegrationSupport.migrate(sharedDataSource);
OutboxIntegrationSupport.migrate(sharedDataSource);
contractContext =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, Clock.systemUTC());
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, Clock.systemUTC());
}
@BeforeEach
@@ -85,23 +85,16 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe
Clock clock = Clock.fixed(t0.plusSeconds(1), ZoneOffset.UTC);
AnnotationConfigApplicationContext seedCtx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock);
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock);
TransactionPort seedTx = seedCtx.getBean(TransactionPort.class);
LegacyOutboxAppendPort appendPort = seedCtx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort appendPort = seedCtx.getBean(OutboxAppendPort.class);
seedTx.inWrite(
() -> {
for (int i = 0; i < 1000; i++) {
String id = "evt-leader-" + i;
appendPort.append(
new NewOutboxEvent(
id,
"TestEvent",
"agg-leader-" + i, // distinct aggregateId per row
"{\"seq\":" + i + "}",
t0, // fixed occurredAt = t0 so next_attempt_at = t0 <= relay now
"corr-leader-" + i,
id));
// distinct aggregate per row; occurredAt = t0 so next_attempt_at = t0 <= relay now
appendPort.append(OutboxEvents.event(id, "agg-leader-" + i, 1, t0));
}
return null;
});
@@ -113,7 +106,7 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe
// ---- build two independent contexts, each with its own stub publisher ----
AnnotationConfigApplicationContext ctx1 =
LegacyOutboxIntegrationSupport.buildContext(
OutboxIntegrationSupport.buildContext(
sharedDataSource,
event -> {
String prev = publishedByEventId.put(event.eventId(), "instance-1");
@@ -124,7 +117,7 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe
clock);
AnnotationConfigApplicationContext ctx2 =
LegacyOutboxIntegrationSupport.buildContext(
OutboxIntegrationSupport.buildContext(
sharedDataSource,
event -> {
String prev = publishedByEventId.put(event.eventId(), "instance-2");
@@ -134,8 +127,8 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe
},
clock);
PublishPendingOutboxEventsUseCase relay1 = LegacyOutboxIntegrationSupport.relayUseCase(ctx1);
PublishPendingOutboxEventsUseCase relay2 = LegacyOutboxIntegrationSupport.relayUseCase(ctx2);
PublishPendingOutboxEventsUseCase relay1 = OutboxIntegrationSupport.relayUseCase(ctx1);
PublishPendingOutboxEventsUseCase relay2 = OutboxIntegrationSupport.relayUseCase(ctx2);
// ---- drive both relay loops concurrently until drained ----
ExecutorService executor = Executors.newFixedThreadPool(2);
@@ -169,7 +162,7 @@ class PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest extends OutboxLeaseFe
}
@Override
protected LegacyOutboxAppendPort append() {
protected OutboxAppendPort append() {
return contractContext.getBean(OutboxStoreAdapter.class);
}
@@ -2,12 +2,12 @@ package dev.caskeleton.adapter.outbound.persistence.readiness;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.outbox.OutboxBackoffPolicy;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
@@ -15,6 +15,7 @@ import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxRelayResult;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
import java.time.Duration;
@@ -46,7 +47,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
* <li>Reaper TTL deletion of PUBLISHED rows
* </ul>
*/
class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
class PostgreSqlOutboxRowLifecycleIntegrationTest {
private static PostgreSqlReadinessSupport postgres;
private static DataSource sharedDataSource;
@@ -55,7 +56,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
static void setup() {
postgres = PostgreSqlReadinessSupport.start();
sharedDataSource = postgres.dataSource();
LegacyOutboxIntegrationSupport.migrate(sharedDataSource);
OutboxIntegrationSupport.migrate(sharedDataSource);
}
@AfterAll
@@ -73,10 +74,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
void pendingRowTransitionsToPublishedOnSuccessfulRelay() {
Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
String eventId = "lifecycle-happy-" + System.nanoTime();
tx.inWrite(
@@ -85,7 +86,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
return null;
});
PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx);
PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx);
OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
long published =
@@ -112,7 +113,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
AtomicBoolean fail = new AtomicBoolean(true);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(
OutboxIntegrationSupport.buildContext(
sharedDataSource,
e -> {
if (fail.get()) {
@@ -122,7 +123,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class);
String eventId = "lifecycle-fail-" + System.nanoTime();
@@ -132,7 +133,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
return null;
});
PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx);
PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx);
OutboxRelayResult result = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
long failed =
@@ -169,7 +170,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
AtomicInteger publishAttempts = new AtomicInteger(0);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(
OutboxIntegrationSupport.buildContext(
sharedDataSource,
e -> {
publishAttempts.incrementAndGet();
@@ -178,7 +179,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
appendClock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class);
String eventId = "lifecycle-dead-" + System.nanoTime();
@@ -242,10 +243,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
Clock clock = Clock.fixed(t0.plusSeconds(1), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
String aggId = "agg-fifo-order-" + System.nanoTime();
String headId = "fifo-order-head-" + System.nanoTime();
@@ -260,7 +261,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
return null;
});
PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx);
PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx);
// --- Relay cycle 1: FIFO gate blocks tail while head is PENDING ---
// The NOT EXISTS gate allows only the head (head has no non-PUBLISHED
@@ -305,16 +306,22 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
}
}
/**
* The gate orders by aggregate sequence, not by time: two events of one aggregate that share an
* {@code occurred_at} are still released one at a time. The pre-canonical gate compared {@code
* occurred_at} with {@code <} and released both together.
*/
@Test
void equalTimestampRowsAreClaimedTogetherLegacyFifoLimitationCharacterization() {
void eventsSharingAnOccurredAtAreReleasedOneAtATimeInAggregateOrder() {
// given
Instant occurredAt = Instant.now();
Clock clock = Clock.fixed(occurredAt.plusSeconds(1), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
String aggregateId = "agg-fifo-tie-" + System.nanoTime();
String firstId = "fifo-tie-first-" + System.nanoTime();
@@ -322,23 +329,22 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
tx.inWrite(
() -> {
append.append(newEventAt(firstId, aggregateId, occurredAt));
append.append(newEventAt(secondId, aggregateId, occurredAt));
append.append(OutboxEvents.event(secondId, aggregateId, 2, occurredAt));
append.append(OutboxEvents.event(firstId, aggregateId, 1, occurredAt));
return null;
});
// when
OutboxRelayResult cycle =
LegacyOutboxIntegrationSupport.relayUseCase(ctx)
OutboxIntegrationSupport.relayUseCase(ctx)
.handle(PublishPendingOutboxEventsCommand.INSTANCE);
// then
assertThat(cycle.outcomes())
.as(
"legacy FIFO compares only occurred_at with '<', so equal timestamps do not gate"
+ " either row")
.filteredOn(
outcome -> outcome.eventId().equals(firstId) || outcome.eventId().equals(secondId))
.extracting(OutboxRelayResult.EventOutcome::eventId)
.containsExactlyInAnyOrder(firstId, secondId);
.containsExactly(firstId);
}
}
@@ -360,7 +366,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
Clock clock = Clock.fixed(t0, ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(
OutboxIntegrationSupport.buildContext(
sharedDataSource,
e -> {
throw new RuntimeException("forced failure for head");
@@ -368,7 +374,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class);
String aggId = "agg-fifo-blocked-" + System.nanoTime();
@@ -386,7 +392,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
// Relay cycle 1: head is claimed and fails → transitions to FAILED
// with nextAttemptAt = t0 + backoff (far in the future).
// Tail is already blocked by the FIFO gate (head is PENDING).
PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx);
PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx);
OutboxRelayResult cycle1 = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
assertThat(
@@ -433,10 +439,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
Clock clock = Clock.fixed(t0.plusSeconds(1), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
String aggId = "agg-fifo-unblock-" + System.nanoTime();
String headId = "fifo-unblock-head-" + System.nanoTime();
@@ -450,7 +456,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
return null;
});
PublishPendingOutboxEventsUseCase relay = LegacyOutboxIntegrationSupport.relayUseCase(ctx);
PublishPendingOutboxEventsUseCase relay = OutboxIntegrationSupport.relayUseCase(ctx);
// Cycle 1: head is claimed and published, tail is blocked.
OutboxRelayResult cycle1 = relay.handle(PublishPendingOutboxEventsCommand.INSTANCE);
@@ -491,7 +497,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
Instant t0 = Instant.now();
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(
OutboxIntegrationSupport.buildContext(
sharedDataSource,
e -> {
throw new RuntimeException("always fails");
@@ -499,7 +505,7 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
Clock.fixed(t0, ZoneOffset.UTC))) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class);
String aggId = "agg-fifo-dead-" + System.nanoTime();
@@ -572,10 +578,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
Clock reclaimClock = Clock.fixed(t0.plus(Duration.ofSeconds(31)), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, claimClock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, claimClock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class);
String eventId = "lifecycle-orphan-" + System.nanoTime();
@@ -603,8 +609,8 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
ctx.getBean(TransactionPort.class),
new OutboxBackoffPolicy(RandomGenerator.getDefault()),
reclaimClock,
LegacyOutboxIntegrationSupport.BATCH_SIZE_CONTRACT,
LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT,
OutboxIntegrationSupport.BATCH_SIZE_CONTRACT,
OutboxIntegrationSupport.IN_FLIGHT_TIMEOUT,
UUID.randomUUID().toString());
OutboxRelayResult reclaimResult =
@@ -630,10 +636,10 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
Clock clock = Clock.fixed(Instant.now(), ZoneOffset.UTC);
try (AnnotationConfigApplicationContext ctx =
LegacyOutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
OutboxIntegrationSupport.buildContext(sharedDataSource, e -> {}, clock)) {
TransactionPort tx = ctx.getBean(TransactionPort.class);
LegacyOutboxAppendPort append = ctx.getBean(LegacyOutboxAppendPort.class);
OutboxAppendPort append = ctx.getBean(OutboxAppendPort.class);
OutboxStoreAdapter store = ctx.getBean(OutboxStoreAdapter.class);
String eventId = "lifecycle-reap-" + System.nanoTime();
@@ -694,23 +700,23 @@ class PostgreSqlLegacyOutboxRowLifecycleIntegrationTest {
ctx.getBean(TransactionPort.class),
new OutboxBackoffPolicy(RandomGenerator.getDefault()),
Clock.fixed(clockInstant, ZoneOffset.UTC),
LegacyOutboxIntegrationSupport.BATCH_SIZE_CONTRACT,
LegacyOutboxIntegrationSupport.IN_FLIGHT_TIMEOUT,
OutboxIntegrationSupport.BATCH_SIZE_CONTRACT,
OutboxIntegrationSupport.IN_FLIGHT_TIMEOUT,
UUID.randomUUID().toString());
}
private static NewOutboxEvent newEvent(String eventId, String aggregateId, Clock clock) {
private static ValidatedIntegrationEvent newEvent(
String eventId, String aggregateId, Clock clock) {
return newEventAt(eventId, aggregateId, clock.instant());
}
private static NewOutboxEvent newEventAt(String eventId, String aggregateId, Instant occurredAt) {
return new NewOutboxEvent(
eventId,
"TestEvent",
aggregateId,
"{\"test\":true}",
occurredAt,
"corr-" + eventId,
eventId);
/**
* An event whose aggregate sequence is its occurrence time in microseconds, so events of one
* aggregate appended in time order are also in aggregate order.
*/
private static ValidatedIntegrationEvent newEventAt(
String eventId, String aggregateId, Instant occurredAt) {
long sequence = occurredAt.getEpochSecond() * 1_000_000L + occurredAt.getNano() / 1_000;
return OutboxEvents.event(eventId, aggregateId, sequence, occurredAt);
}
}
@@ -23,7 +23,7 @@ class CandidateAdapterCompositionTest {
@DisplayName("the idempotency store that already fixed this stays fixed")
void theIdempotencyStoreThatAlreadyFixedThisStaysFixed() {
Class<?> store =
dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency
dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql
.PostgreSqlOwnerSafeIdempotencyStore.class;
assertThat(store.getAnnotation(Repository.class))
@@ -79,6 +79,9 @@ class JpaModuleBoundaryTest {
"config",
"h2",
"hibernate",
// The PostgreSQL idempotency store, which lives with its feature
// (idempotency.postgresql) and is registered from here.
"idempotency",
"notification",
"observation",
"postgresql",
@@ -2,8 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.autoconfigure;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream;
import dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore;
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream;
import dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore;
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa;
import static org.assertj.core.api.Assertions.assertThat;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import static org.assertj.core.api.Assertions.assertThat;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency;
package dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
@@ -1,64 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
class CanonicalOutboxAppendAdapterActivationTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(TestConfig.class);
@Test
void canonicalFlagAloneDoesNotExposeAppendWhenOutboxCapabilityIsOff() {
runner
.withPropertyValues(
"ca-skeleton.outbox.enabled=false",
"ca-skeleton.outbox.canonical-transport-enabled=true")
.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(OutboxAppendPort.class);
});
}
@Test
void bothOutboxAndCanonicalFlagsExposeExactlyOneCanonicalAppendPort() {
runner
.withPropertyValues(
"ca-skeleton.outbox.enabled=true",
"ca-skeleton.outbox.canonical-transport-enabled=true")
.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).hasSingleBean(OutboxAppendPort.class);
assertThat(context.getBean(OutboxAppendPort.class))
.isInstanceOf(CanonicalOutboxAppendAdapter.class);
});
}
@Test
void defaultOffDoesNotExposeCanonicalAppendPort() {
runner.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).doesNotHaveBean(OutboxAppendPort.class);
});
}
@Configuration(proxyBeanMethods = false)
@Import(CanonicalOutboxAppendAdapter.class)
static class TestConfig {
@Bean
OutboxEventJpaRepository outboxEventJpaRepository() {
return mock(OutboxEventJpaRepository.class);
}
}
}
@@ -1,143 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentCaptor.forClass;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.transaction.support.TransactionSynchronizationManager;
class CanonicalOutboxAppendAdapterTest {
private static final Instant OCCURRED_AT = Instant.parse("2026-09-18T03:00:00Z");
private final OutboxEventJpaRepository repository = mock(OutboxEventJpaRepository.class);
private final CanonicalOutboxAppendAdapter adapter = new CanonicalOutboxAppendAdapter(repository);
@BeforeEach
void openCallerTransactionBoundary() {
TransactionSynchronizationManager.setActualTransactionActive(true);
}
@AfterEach
void clearCallerTransactionBoundary() {
TransactionSynchronizationManager.clear();
}
@Test
void appendOutsideACallerTransactionIsRefusedBeforeAnyWrite() {
// given
TransactionSynchronizationManager.setActualTransactionActive(false);
ValidatedIntegrationEvent event = event("{}".getBytes(StandardCharsets.UTF_8));
// when
Throwable thrown = catchThrowable(() -> adapter.append(event));
// then
assertThat(thrown)
.isInstanceOf(IllegalStateException.class)
.hasMessage("outbox append requires an active caller transaction");
}
@Test
void appendPersistsExactCanonicalMetadataAndLegacyCompatibilityProjection() {
byte[] exactEnvelope =
"{\"event\":\"canonical\",\"value\":\"한글\"}".getBytes(StandardCharsets.UTF_8);
ValidatedIntegrationEvent event = event(exactEnvelope);
adapter.append(event);
ArgumentCaptor<OutboxEventEntity> saved = forClass(OutboxEventEntity.class);
verify(repository).save(saved.capture());
OutboxEventEntity entity = saved.getValue();
assertThat(entity.getEventId()).isEqualTo("01994e11-4d88-7000-8000-000000000001");
assertThat(entity.getEventType()).isEqualTo("portfolio.worklog.reserved");
assertThat(entity.getAggregateId()).isEqualTo("worklog-42");
assertThat(entity.getPayload()).isEqualTo(new String(exactEnvelope, StandardCharsets.UTF_8));
assertThat(entity.getOccurredAt()).isEqualTo(OCCURRED_AT);
assertThat(entity.getStatus()).isEqualTo("PENDING");
assertThat(entity.getAttemptCount()).isZero();
assertThat(entity.getNextAttemptAt()).isEqualTo(OCCURRED_AT);
assertThat(entity.getCorrelationId()).isEqualTo("corr-1");
assertThat(entity.getIdempotencyKey()).isEqualTo(event.eventId().value());
assertThat(entity.getContractId()).isEqualTo("portfolio.worklog.reserved");
assertThat(entity.getEnvelopeVersion()).isEqualTo(1);
assertThat(entity.getPayloadVersion()).isEqualTo(3);
assertThat(entity.getLogicalDestination()).isEqualTo("portfolio-domain-events");
assertThat(entity.getTenantScope()).isEqualTo("tenant-a");
assertThat(entity.getAggregateType()).isEqualTo("worklog");
assertThat(entity.getAggregateSequence()).isEqualTo(17L);
assertThat(entity.getEventIndex()).isEqualTo(2);
assertThat(entity.getPartitionKey()).isEqualTo("a".repeat(64));
assertThat(entity.getEnvelopeBytes()).containsExactly(exactEnvelope);
assertThat(entity.getContentType()).isEqualTo("application/json");
assertThat(entity.getSchemaSetHash()).isEqualTo("1".repeat(64));
assertThat(entity.getEnvelopeSha256()).isEqualTo(Sha256.of(exactEnvelope).toString());
assertThat(entity.getEnvelopeSchemaHash()).isEqualTo("3".repeat(64));
assertThat(entity.getPayloadSchemaHash()).isEqualTo("4".repeat(64));
assertThat(entity.getContractCatalogRevision()).isEqualTo("catalog-r1");
assertThat(entity.getDestinationBindingRevision()).isEqualTo("binding-r1");
assertThat(entity.getCausationId()).isEqualTo("01994e11-4d88-7000-8000-000000000000");
}
@Test
void invalidUtf8EnvelopeIsRejectedBeforeRepositoryWrite() {
ValidatedIntegrationEvent event = event(new byte[] {(byte) 0xC3, (byte) 0x28});
assertThatThrownBy(() -> adapter.append(event))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("UTF-8")
.hasMessageContaining("compatibility");
verifyNoInteractions(repository);
}
private static ValidatedIntegrationEvent event(byte[] envelopeBytes) {
String partition = "a".repeat(64);
return new ValidatedIntegrationEvent(
new EventId("01994e11-4d88-7000-8000-000000000001"),
new ContractId("portfolio.worklog.reserved"),
1,
3,
new LogicalDestinationId("portfolio-domain-events"),
new AggregateIdentity("tenant-a", "worklog", "worklog-42"),
new AggregateOrder(17, 2),
OCCURRED_AT,
"corr-1",
Optional.of("01994e11-4d88-7000-8000-000000000000"),
partition,
partition.getBytes(StandardCharsets.US_ASCII),
envelopeBytes,
"application/json",
sha("1"),
Sha256.of(envelopeBytes),
sha("3"),
sha("4"),
"catalog-r1",
"binding-r1");
}
private static Sha256 sha(String nibble) {
return new Sha256(java.util.HexFormat.of().parseHex(nibble.repeat(64)));
}
}
@@ -1,401 +0,0 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentCaptor.forClass;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.outbox.CanonicalClaimedOutboxEvent;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.application.outbox.OutboxCompletion;
import dev.caskeleton.application.outbox.OutboxEvent;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Unit tests for {@link OutboxStoreAdapter} — covers append mapping, claim transition, mark
* operations, countByStatus, and oldestUnpublishedAgeSecondsByEventType.
*
* <h2>FIFO gate location contract</h2>
*
* <p>The per-aggregate FIFO gate (I4) lives entirely in the {@link
* OutboxClaimRepository#claimEligible} native SQL query via a {@code NOT EXISTS} correlated
* subquery. The adapter itself performs NO in-memory filtering: every row returned by the claim
* repository passes through to the caller. Verifying that the SQL gate enforces FIFO is the
* responsibility of the Testcontainers contract test in {@code app-bootstrap}.
*
* <p>Real SKIP LOCKED / FIFO gate behaviour is covered by the Task E PG contract tests.
*/
class OutboxStoreAdapterTest {
private static final Instant NOW = Instant.parse("2026-06-11T10:00:00Z");
private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(5);
private final OutboxEventJpaRepository repo = mock(OutboxEventJpaRepository.class);
private final OutboxClaimRepository claimRepo = mock(OutboxClaimRepository.class);
private final OutboxStoreAdapter adapter = new OutboxStoreAdapter(repo, claimRepo);
@BeforeEach
void openCallerTransactionBoundary() {
TransactionSynchronizationManager.setActualTransactionActive(true);
}
@AfterEach
void clearCallerTransactionBoundary() {
TransactionSynchronizationManager.clear();
}
// ---- helper ----
private static final String OWNER = "relay-1";
private static OutboxLease lease(String eventId) {
return new OutboxLease(
new OutboxEvent(
eventId,
"UserCreated",
"agg-1",
"{}",
NOW,
"corr-1",
"idem-1",
OutboxEventStatus.IN_FLIGHT,
1),
OWNER,
1);
}
private static NewOutboxEvent newEvent(String eventId) {
return new NewOutboxEvent(eventId, "UserCreated", "agg-1", "{}", NOW, "corr-1", "idem-1");
}
private static OutboxEventEntity pendingEntity(String eventId) {
OutboxEventEntity e = new OutboxEventEntity();
e.setEventId(eventId);
e.setAggregateId("agg-1");
e.setEventType("UserCreated");
e.setPayload("{}");
e.setOccurredAt(NOW.minusSeconds(60));
e.setStatus("PENDING");
e.setAttemptCount(0);
e.setNextAttemptAt(NOW.minusSeconds(60));
e.setCorrelationId("corr-1");
e.setIdempotencyKey("idem-1");
return e;
}
private static OutboxEventEntity canonicalPendingEntity(String eventId) {
OutboxEventEntity e = pendingEntity(eventId);
byte[] envelope = "{\"wire\":\"exact\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8);
e.setAggregateId("worklog-42");
e.setEventType("portfolio.worklog.reserved");
e.setPayload(new String(envelope, java.nio.charset.StandardCharsets.UTF_8));
e.setCorrelationId("corr-1");
e.setIdempotencyKey(eventId);
e.setContractId("portfolio.worklog.reserved");
e.setEnvelopeVersion(1);
e.setPayloadVersion(3);
e.setLogicalDestination("portfolio-domain-events");
e.setTenantScope("tenant-a");
e.setAggregateType("worklog");
e.setAggregateSequence(17L);
e.setEventIndex(2);
e.setPartitionKey("a".repeat(64));
e.setEnvelopeBytes(envelope);
e.setContentType("application/json");
e.setSchemaSetHash("1".repeat(64));
e.setEnvelopeSha256(Sha256.of(envelope).toString());
e.setEnvelopeSchemaHash("3".repeat(64));
e.setPayloadSchemaHash("4".repeat(64));
e.setContractCatalogRevision("catalog-r1");
e.setDestinationBindingRevision("binding-r1");
e.setCausationId("01994e11-4d88-7000-8000-000000000000");
return e;
}
// ---- append ----
@Test
void appendPersistsEntityWithCorrectFieldMapping() {
NewOutboxEvent event = newEvent("evt-001");
adapter.append(event);
ArgumentCaptor<OutboxEventEntity> saved = forClass(OutboxEventEntity.class);
verify(repo).save(saved.capture());
OutboxEventEntity entity = saved.getValue();
assertThat(entity.getEventId()).isEqualTo("evt-001");
assertThat(entity.getEventType()).isEqualTo("UserCreated");
assertThat(entity.getAggregateId()).isEqualTo("agg-1");
assertThat(entity.getPayload()).isEqualTo("{}");
assertThat(entity.getOccurredAt()).isEqualTo(NOW);
assertThat(entity.getStatus()).isEqualTo("PENDING");
assertThat(entity.getAttemptCount()).isEqualTo(0);
assertThat(entity.getNextAttemptAt()).isEqualTo(NOW); // nextAttemptAt = occurredAt on PENDING
assertThat(entity.getCorrelationId()).isEqualTo("corr-1");
assertThat(entity.getIdempotencyKey()).isEqualTo("idem-1");
}
// ---- claimBatch ----
@Test
void claimAndMarkOperationsRejectAMissingCallerTransaction() {
TransactionSynchronizationManager.clear();
assertThatThrownBy(() -> adapter.append(newEvent("evt-append-guard")))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("append")
.hasMessageContaining("active caller transaction");
assertThatThrownBy(() -> adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("claimBatch")
.hasMessageContaining("active caller transaction");
assertThatThrownBy(() -> adapter.markPublished(lease("evt-guard")))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("markPublished");
assertThatThrownBy(() -> adapter.markFailed(lease("evt-guard"), NOW.plusSeconds(1)))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("markFailed");
assertThatThrownBy(() -> adapter.markDead(lease("evt-guard")))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("markDead");
}
@Test
void claimBatchTransitionsEntityToInFlightAndReturnsMappedEvent() {
OutboxEventEntity entity = pendingEntity("evt-002");
when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity));
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT);
// status, attemptCount and the lease updated on the locked entity
assertThat(entity.getStatus()).isEqualTo("IN_FLIGHT");
assertThat(entity.getAttemptCount()).isEqualTo(1);
assertThat(entity.getNextAttemptAt()).isEqualTo(NOW.plus(IN_FLIGHT_TIMEOUT));
assertThat(entity.getLeaseOwner()).isEqualTo(OWNER);
assertThat(entity.getLeaseToken()).isEqualTo(1);
assertThat(claimed.get(0).token()).isEqualTo(1);
// returned OutboxEvent reflects post-transition state
assertThat(claimed).hasSize(1);
OutboxEvent result = (OutboxEvent) claimed.get(0).event();
assertThat(result.eventId()).isEqualTo("evt-002");
assertThat(result.status()).isEqualTo(OutboxEventStatus.IN_FLIGHT);
assertThat(result.attemptCount()).isEqualTo(1);
}
@Test
void reclaimTakesTheRowOverWithTheNextToken() {
// given
OutboxEventEntity orphan = pendingEntity("evt-orphan");
orphan.setStatus("IN_FLIGHT");
orphan.setLeaseOwner("stalled-relay");
orphan.setLeaseToken(4);
when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(orphan));
// when
OutboxLease lease = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT).getFirst();
// then
assertThat(
List.of(lease.owner(), lease.token(), orphan.getLeaseOwner(), orphan.getLeaseToken()))
.containsExactly(OWNER, 5L, OWNER, 5L);
}
@Test
void claimBatchMapsCompleteCanonicalMetadataToCanonicalClaim() {
OutboxEventEntity entity = canonicalPendingEntity("01994e11-4d88-7000-8000-000000000001");
when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity));
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT);
assertThat(claimed).hasSize(1);
assertThat(claimed.getFirst().event()).isInstanceOf(CanonicalClaimedOutboxEvent.class);
CanonicalClaimedOutboxEvent result = (CanonicalClaimedOutboxEvent) claimed.getFirst().event();
assertThat(result.event().eventId().value()).isEqualTo("01994e11-4d88-7000-8000-000000000001");
assertThat(result.event().contractId().value()).isEqualTo("portfolio.worklog.reserved");
assertThat(result.event().aggregate().tenantScope()).isEqualTo("tenant-a");
assertThat(result.event().aggregate().aggregateType()).isEqualTo("worklog");
assertThat(result.event().order().sequence()).isEqualTo(17);
assertThat(result.event().order().eventIndex()).isEqualTo(2);
assertThat(result.event().envelopeBytes())
.containsExactly("{\"wire\":\"exact\"}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
assertThat(result.status()).isEqualTo(OutboxEventStatus.IN_FLIGHT);
assertThat(result.attemptCount()).isEqualTo(1);
}
/**
* Partial canonical metadata still fails closed — it is never downgraded to a legacy claim — but
* it fails that one row. Throwing out of the claim rolled the whole batch back, and the next
* claim selected the same row first, so one bad row stopped the relay for good.
*/
@Test
void claimBatchMovesAnUnreadableRowToDeadAndClaimsTheRestOfTheBatch() {
// given
OutboxEventEntity partial = pendingEntity("partial-canonical");
partial.setEnvelopeVersion(1);
when(claimRepo.claimEligible(eq(NOW), eq(2)))
.thenReturn(List.of(partial, pendingEntity("evt-readable")));
// when
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT);
// then
assertThat(List.of(claimed.stream().map(OutboxLease::eventId).toList(), partial.getStatus()))
.containsExactly(List.of("evt-readable"), "DEAD");
}
@Test
void claimBatchMovesACanonicalRowWhoseStoredEnvelopeHashIsNotItsBytesHashToDead() {
// given
OutboxEventEntity entity = canonicalPendingEntity("01994e11-4d88-7000-8000-000000000001");
entity.setEnvelopeSha256("2".repeat(64));
when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(entity));
// when
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT);
// then
assertThat(List.of(claimed, entity.getStatus())).containsExactly(List.of(), "DEAD");
}
@Test
void claimBatchReturnsEmptyWhenRepoReturnsNothing() {
when(claimRepo.claimEligible(any(), anyInt())).thenReturn(List.of());
assertThat(adapter.claimBatch(OWNER, 5, NOW, IN_FLIGHT_TIMEOUT)).isEmpty();
}
/**
* Regression guard: the per-aggregate FIFO gate lives in the SQL query (I4). The adapter must NOT
* apply any in-memory filtering — all rows returned by the repository must appear in the result,
* including multiple rows for the same aggregate.
*
* <p>If this test fails it means in-memory filtering was re-introduced in the adapter; the fix is
* to move that logic back to the {@code claimEligible} SQL query.
*/
@Test
void claimBatchPassesAllRepoResultsThroughWithoutInMemoryFifoFiltering() {
// Two rows for the same aggregate — repo returns both (SQL gate already enforces FIFO)
OutboxEventEntity head = pendingEntity("evt-head");
OutboxEventEntity tail = new OutboxEventEntity();
tail.setEventId("evt-tail");
tail.setAggregateId("agg-1"); // same aggregate as head
tail.setEventType("UserCreated");
tail.setPayload("{}");
tail.setOccurredAt(NOW.minusSeconds(30)); // later than head (head is at -60s)
tail.setStatus("PENDING");
tail.setAttemptCount(0);
tail.setNextAttemptAt(NOW.minusSeconds(30));
tail.setCorrelationId("corr-2");
tail.setIdempotencyKey("idem-2");
when(claimRepo.claimEligible(eq(NOW), eq(10))).thenReturn(List.of(head, tail));
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 10, NOW, IN_FLIGHT_TIMEOUT);
// Adapter must return both rows — no in-memory FIFO filtering
assertThat(claimed)
.hasSize(2)
.extracting(OutboxLease::eventId)
.containsExactly("evt-head", "evt-tail");
}
// ---- completions: one conditional UPDATE under the lease ----
@Test
void markPublishedCompletesOnlyUnderTheLease() {
when(repo.completeLease("evt-003", OWNER, 1, "PUBLISHED")).thenReturn(1);
assertThat(adapter.markPublished(lease("evt-003"))).isEqualTo(OutboxCompletion.APPLIED);
}
@Test
void markFailedCompletesOnlyUnderTheLeaseAndSchedulesTheRetry() {
Instant retryAt = NOW.plus(Duration.ofSeconds(30));
when(repo.failLease("evt-004", OWNER, 1, retryAt)).thenReturn(1);
assertThat(adapter.markFailed(lease("evt-004"), retryAt)).isEqualTo(OutboxCompletion.APPLIED);
}
@Test
void markDeadCompletesOnlyUnderTheLease() {
when(repo.completeLease("evt-005", OWNER, 1, "DEAD")).thenReturn(1);
assertThat(adapter.markDead(lease("evt-005"))).isEqualTo(OutboxCompletion.APPLIED);
}
/**
* Zero rows means the lease no longer holds the row — another relay reclaimed it after the
* in-flight timeout, or it is already complete. That relay owns the row, so this is a result, not
* an error, and nothing is loaded and overwritten.
*/
@Test
void aCompletionThatMatchesNoRowIsStale() {
when(repo.completeLease("evt-stale", OWNER, 1, "PUBLISHED")).thenReturn(0);
OutboxCompletion completion = adapter.markPublished(lease("evt-stale"));
assertThat(completion).isEqualTo(OutboxCompletion.STALE);
verify(repo, never()).findById(any());
}
// ---- countByStatus ----
@Test
void countByStatusMapsProjectionResultsToStatusEnumMap() {
List<Object[]> rows =
List.of(
new Object[] {"PENDING", 5L},
new Object[] {"IN_FLIGHT", 2L},
new Object[] {"PUBLISHED", 10L});
when(repo.countGroupedByStatus()).thenReturn(rows);
Map<OutboxEventStatus, Long> counts = adapter.countByStatus();
assertThat(counts).containsEntry(OutboxEventStatus.PENDING, 5L);
assertThat(counts).containsEntry(OutboxEventStatus.IN_FLIGHT, 2L);
assertThat(counts).containsEntry(OutboxEventStatus.PUBLISHED, 10L);
assertThat(counts).doesNotContainKey(OutboxEventStatus.FAILED);
assertThat(counts).doesNotContainKey(OutboxEventStatus.DEAD);
}
// ---- oldestUnpublishedAgeSecondsByEventType ----
@Test
void oldestUnpublishedAgeComputesSecondsFromOldestRowOccurredAt() {
// oldest row for "UserCreated" occurred 120 seconds before NOW
Instant oldestAt = NOW.minusSeconds(120);
List<Object[]> rows = List.<Object[]>of(new Object[] {"UserCreated", oldestAt});
when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(rows);
Map<String, Long> ages = adapter.oldestUnpublishedAgeSecondsByEventType(NOW);
assertThat(ages).containsEntry("UserCreated", 120L);
}
@Test
void oldestUnpublishedAgeReturnsEmptyMapWhenNoUnpublishedRows() {
when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(List.of());
assertThat(adapter.oldestUnpublishedAgeSecondsByEventType(NOW)).isEmpty();
}
}
@@ -1,9 +1,9 @@
package dev.caskeleton.adapter.outbound.persistence.h2;
package dev.caskeleton.adapter.outbound.persistence.outbox.h2;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import java.time.Instant;
@@ -58,7 +58,7 @@ class H2ClaimSqlTest {
factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setPersistenceUnitName("h2-claim-sql");
factoryBean.setPackagesToScan("dev.caskeleton.adapter.outbound.persistence.outbox.entity");
factoryBean.setPackagesToScan("dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity");
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setJpaProperties(jpaProperties);
factoryBean.afterPropertiesSet();
@@ -165,9 +165,6 @@ class H2ClaimSqlTest {
private OutboxEventEntity canonical(String eventId, long sequence, int eventIndex) {
OutboxEventEntity entity = event(eventId, "worklog-42", now.minusSeconds(60), now);
entity.setContractId("portfolio.worklog.reserved");
entity.setTenantScope("tenant-a");
entity.setAggregateType("worklog");
entity.setAggregateSequence(sequence);
entity.setEventIndex(eventIndex);
return entity;
@@ -178,19 +175,27 @@ class H2ClaimSqlTest {
entityManager -> new H2OutboxClaimRepository(entityManager).claimEligible(asOf, limit));
}
/**
* A row as the append writes it, reduced to the columns the claim reads. Its aggregate sequence
* is its occurrence second, so rows of one aggregate appended in time order are in aggregate
* order.
*/
private static OutboxEventEntity event(
String eventId, String aggregateId, Instant occurredAt, Instant nextAttemptAt) {
OutboxEventEntity entity = new OutboxEventEntity();
entity.setEventId(eventId);
entity.setAggregateId(aggregateId);
entity.setEventType("OrderPlaced");
entity.setPayload("{}");
entity.setEventType("portfolio.worklog.reserved");
entity.setOccurredAt(occurredAt);
entity.setStatus("PENDING");
entity.setAttemptCount(0);
entity.setNextAttemptAt(nextAttemptAt);
entity.setCorrelationId("corr-1");
entity.setIdempotencyKey("idem-" + eventId);
entity.setContractId("portfolio.worklog.reserved");
entity.setTenantScope("tenant-a");
entity.setAggregateType("worklog");
entity.setAggregateSequence(occurredAt.getEpochSecond());
entity.setEventIndex(0);
return entity;
}
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
@@ -0,0 +1,435 @@
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentCaptor.forClass;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.EventId;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxCompletion;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxLease;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Unit tests for {@link OutboxStoreAdapter} — covers append mapping, claim transition, mark
* operations, countByStatus, and oldestUnpublishedAgeSecondsByEventType.
*
* <h2>FIFO gate location contract</h2>
*
* <p>The per-aggregate FIFO gate (I4) lives entirely in the {@link
* OutboxClaimRepository#claimEligible} native SQL query via a {@code NOT EXISTS} correlated
* subquery. The adapter itself performs NO in-memory filtering: every row returned by the claim
* repository passes through to the caller. Real SKIP LOCKED / FIFO gate behaviour is covered by the
* PostgreSQL outbox integration tests.
*/
class OutboxStoreAdapterTest {
private static final Instant NOW = Instant.parse("2026-06-11T10:00:00Z");
private static final Instant OCCURRED_AT = NOW.minusSeconds(60);
private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(5);
private static final String OWNER = "relay-1";
private static final byte[] ENVELOPE =
"{\"event\":\"canonical\",\"value\":\"한글\"}".getBytes(StandardCharsets.UTF_8);
private final OutboxEventJpaRepository repo = mock(OutboxEventJpaRepository.class);
private final OutboxClaimRepository claimRepo = mock(OutboxClaimRepository.class);
private final OutboxStoreAdapter adapter = new OutboxStoreAdapter(repo, claimRepo);
@BeforeEach
void openCallerTransactionBoundary() {
TransactionSynchronizationManager.setActualTransactionActive(true);
}
@AfterEach
void clearCallerTransactionBoundary() {
TransactionSynchronizationManager.clear();
}
// ---- append ----
@Test
void appendStoresTheExactEnvelopeAndEveryCanonicalIdentity() {
// given
ValidatedIntegrationEvent event = event("evt-001", "worklog-42");
// when
adapter.append(event);
// then
ArgumentCaptor<OutboxEventEntity> saved = forClass(OutboxEventEntity.class);
verify(repo).save(saved.capture());
OutboxEventEntity entity = saved.getValue();
assertThat(entity)
.extracting(
OutboxEventEntity::getEventId,
OutboxEventEntity::getEventType,
OutboxEventEntity::getAggregateId,
OutboxEventEntity::getOccurredAt,
OutboxEventEntity::getStatus,
OutboxEventEntity::getAttemptCount,
OutboxEventEntity::getNextAttemptAt,
OutboxEventEntity::getCorrelationId,
OutboxEventEntity::getContractId,
OutboxEventEntity::getEnvelopeVersion,
OutboxEventEntity::getPayloadVersion,
OutboxEventEntity::getLogicalDestination,
OutboxEventEntity::getTenantScope,
OutboxEventEntity::getAggregateType,
OutboxEventEntity::getAggregateSequence,
OutboxEventEntity::getEventIndex,
OutboxEventEntity::getPartitionKey,
OutboxEventEntity::getContentType,
OutboxEventEntity::getSchemaSetHash,
OutboxEventEntity::getEnvelopeSha256,
OutboxEventEntity::getEnvelopeSchemaHash,
OutboxEventEntity::getPayloadSchemaHash,
OutboxEventEntity::getContractCatalogRevision,
OutboxEventEntity::getDestinationBindingRevision,
OutboxEventEntity::getCausationId)
.containsExactly(
"evt-001",
"portfolio.worklog.reserved",
"worklog-42",
OCCURRED_AT,
"PENDING",
0,
OCCURRED_AT,
"corr-1",
"portfolio.worklog.reserved",
1,
3,
"portfolio-domain-events",
"tenant-a",
"worklog",
17L,
2,
"a".repeat(64),
"application/json",
"1".repeat(64),
Sha256.of(ENVELOPE).toString(),
"3".repeat(64),
"4".repeat(64),
"catalog-r1",
"binding-r1",
"01994e11-4d88-7000-8000-000000000000");
}
@Test
void appendKeepsTheEnvelopeBytesExactly() {
// when
adapter.append(event("evt-bytes", "worklog-42"));
// then
ArgumentCaptor<OutboxEventEntity> saved = forClass(OutboxEventEntity.class);
verify(repo).save(saved.capture());
assertThat(saved.getValue().getEnvelopeBytes()).containsExactly(ENVELOPE);
}
@Test
void appendOutsideACallerTransactionIsRefusedBeforeAnyWrite() {
// given
TransactionSynchronizationManager.clear();
// when
Throwable thrown = catchThrowable(() -> adapter.append(event("evt-guard", "worklog-42")));
// then
assertThat(thrown)
.isInstanceOf(IllegalStateException.class)
.hasMessage("outbox append requires an active caller transaction");
verifyNoInteractions(repo);
}
// ---- claimBatch ----
@Test
void claimAndMarkOperationsRejectAMissingCallerTransaction() {
TransactionSynchronizationManager.clear();
assertThatThrownBy(() -> adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("claimBatch")
.hasMessageContaining("active caller transaction");
assertThatThrownBy(() -> adapter.markPublished(lease("evt-guard")))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("markPublished");
assertThatThrownBy(() -> adapter.markFailed(lease("evt-guard"), NOW.plusSeconds(1)))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("markFailed");
assertThatThrownBy(() -> adapter.markDead(lease("evt-guard")))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("markDead");
}
@Test
void claimBatchTransitionsTheRowToInFlightUnderANewLease() {
// given
OutboxEventEntity entity = pendingEntity("evt-002", "worklog-42");
when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(entity));
// when
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT);
// then
assertThat(
List.of(
entity.getStatus(),
entity.getAttemptCount(),
entity.getNextAttemptAt(),
entity.getLeaseOwner(),
entity.getLeaseToken(),
claimed.getFirst().token()))
.containsExactly("IN_FLIGHT", 1, NOW.plus(IN_FLIGHT_TIMEOUT), OWNER, 1L, 1L);
}
@Test
void claimBatchRestoresTheAppendedEventFromTheStoredEnvelope() {
// given
OutboxEventEntity entity = pendingEntity("evt-restore", "worklog-42");
when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(entity));
// when
ClaimedOutboxEvent claimed =
adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT).getFirst().event();
// then
assertThat(claimed)
.isEqualTo(
new ClaimedOutboxEvent(
event("evt-restore", "worklog-42"), OutboxEventStatus.IN_FLIGHT, 1));
}
@Test
void reclaimTakesTheRowOverWithTheNextToken() {
// given
OutboxEventEntity orphan = pendingEntity("evt-orphan", "worklog-42");
orphan.setStatus("IN_FLIGHT");
orphan.setLeaseOwner("stalled-relay");
orphan.setLeaseToken(4);
when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(orphan));
// when
OutboxLease lease = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT).getFirst();
// then
assertThat(
List.of(lease.owner(), lease.token(), orphan.getLeaseOwner(), orphan.getLeaseToken()))
.containsExactly(OWNER, 5L, OWNER, 5L);
}
/**
* A row without the canonical envelope — written by the pre-canonical append, or damaged — is
* unreadable. It fails that one row, never the batch: throwing out of the claim rolled the whole
* batch back, and the next claim selected the same row first, so one bad row stopped the relay.
*/
@Test
void claimBatchMovesARowWithoutTheCanonicalEnvelopeToDeadAndClaimsTheRest() {
// given
OutboxEventEntity preCanonical = pendingEntity("pre-canonical", "worklog-7");
preCanonical.setEnvelopeBytes(null);
OutboxEventEntity readable = pendingEntity("evt-readable", "worklog-42");
when(claimRepo.claimEligible(eq(NOW), eq(2))).thenReturn(List.of(preCanonical, readable));
// when
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 2, NOW, IN_FLIGHT_TIMEOUT);
// then
assertThat(
List.of(claimed.stream().map(OutboxLease::eventId).toList(), preCanonical.getStatus()))
.containsExactly(List.of("evt-readable"), "DEAD");
}
@Test
void claimBatchMovesARowWhoseStoredEnvelopeHashIsNotItsBytesHashToDead() {
// given
OutboxEventEntity entity = pendingEntity("evt-tampered", "worklog-42");
entity.setEnvelopeSha256("2".repeat(64));
when(claimRepo.claimEligible(eq(NOW), eq(1))).thenReturn(List.of(entity));
// when
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 1, NOW, IN_FLIGHT_TIMEOUT);
// then
assertThat(List.of(claimed, entity.getStatus())).containsExactly(List.of(), "DEAD");
}
@Test
void claimBatchReturnsEmptyWhenRepoReturnsNothing() {
when(claimRepo.claimEligible(any(), anyInt())).thenReturn(List.of());
assertThat(adapter.claimBatch(OWNER, 5, NOW, IN_FLIGHT_TIMEOUT)).isEmpty();
}
/**
* Regression guard: the per-aggregate FIFO gate lives in the SQL query (I4). The adapter must NOT
* apply any in-memory filtering — all rows returned by the repository must appear in the result,
* including multiple rows for the same aggregate.
*/
@Test
void claimBatchPassesAllRepoResultsThroughWithoutInMemoryFifoFiltering() {
// given
OutboxEventEntity head = pendingEntity("evt-head", "worklog-42");
OutboxEventEntity tail = pendingEntity("evt-tail", "worklog-42");
when(claimRepo.claimEligible(eq(NOW), eq(10))).thenReturn(List.of(head, tail));
// when
List<OutboxLease> claimed = adapter.claimBatch(OWNER, 10, NOW, IN_FLIGHT_TIMEOUT);
// then
assertThat(claimed).extracting(OutboxLease::eventId).containsExactly("evt-head", "evt-tail");
}
// ---- completions: one conditional UPDATE under the lease ----
@Test
void markPublishedCompletesOnlyUnderTheLease() {
when(repo.completeLease("evt-003", OWNER, 1, "PUBLISHED")).thenReturn(1);
assertThat(adapter.markPublished(lease("evt-003"))).isEqualTo(OutboxCompletion.APPLIED);
}
@Test
void markFailedCompletesOnlyUnderTheLeaseAndSchedulesTheRetry() {
Instant retryAt = NOW.plus(Duration.ofSeconds(30));
when(repo.failLease("evt-004", OWNER, 1, retryAt)).thenReturn(1);
assertThat(adapter.markFailed(lease("evt-004"), retryAt)).isEqualTo(OutboxCompletion.APPLIED);
}
@Test
void markDeadCompletesOnlyUnderTheLease() {
when(repo.completeLease("evt-005", OWNER, 1, "DEAD")).thenReturn(1);
assertThat(adapter.markDead(lease("evt-005"))).isEqualTo(OutboxCompletion.APPLIED);
}
/**
* Zero rows means the lease no longer holds the row — another relay reclaimed it after the
* in-flight timeout, or it is already complete. That relay owns the row, so this is a result, not
* an error, and nothing is loaded and overwritten.
*/
@Test
void aCompletionThatMatchesNoRowIsStale() {
when(repo.completeLease("evt-stale", OWNER, 1, "PUBLISHED")).thenReturn(0);
OutboxCompletion completion = adapter.markPublished(lease("evt-stale"));
assertThat(completion).isEqualTo(OutboxCompletion.STALE);
verify(repo, never()).findById(any());
}
// ---- countByStatus ----
@Test
void countByStatusMapsProjectionResultsToStatusEnumMap() {
// given
List<Object[]> rows = List.of(new Object[] {"PENDING", 5L}, new Object[] {"IN_FLIGHT", 2L});
when(repo.countGroupedByStatus()).thenReturn(rows);
// when
Map<OutboxEventStatus, Long> counts = adapter.countByStatus();
// then
assertThat(counts)
.containsExactlyInAnyOrderEntriesOf(
Map.of(OutboxEventStatus.PENDING, 5L, OutboxEventStatus.IN_FLIGHT, 2L));
}
// ---- oldestUnpublishedAgeSecondsByEventType ----
@Test
void oldestUnpublishedAgeComputesSecondsFromOldestRowOccurredAt() {
// given
Instant oldestAt = NOW.minusSeconds(120);
List<Object[]> rows = List.<Object[]>of(new Object[] {"portfolio.worklog.reserved", oldestAt});
when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(rows);
// when
Map<String, Long> ages = adapter.oldestUnpublishedAgeSecondsByEventType(NOW);
// then
assertThat(ages).containsExactly(Map.entry("portfolio.worklog.reserved", 120L));
}
@Test
void oldestUnpublishedAgeReturnsEmptyMapWhenNoUnpublishedRows() {
when(repo.findOldestUnpublishedOccurredAtByEventType()).thenReturn(List.of());
assertThat(adapter.oldestUnpublishedAgeSecondsByEventType(NOW)).isEmpty();
}
// ---- helpers ----
private static OutboxLease lease(String eventId) {
return new OutboxLease(
new ClaimedOutboxEvent(event(eventId, "worklog-42"), OutboxEventStatus.IN_FLIGHT, 1),
OWNER,
1);
}
private static ValidatedIntegrationEvent event(String eventId, String aggregateId) {
String partition = "a".repeat(64);
return new ValidatedIntegrationEvent(
new EventId(eventId),
new ContractId("portfolio.worklog.reserved"),
1,
3,
new LogicalDestinationId("portfolio-domain-events"),
new AggregateIdentity("tenant-a", "worklog", aggregateId),
new AggregateOrder(17, 2),
OCCURRED_AT,
"corr-1",
Optional.of("01994e11-4d88-7000-8000-000000000000"),
partition,
partition.getBytes(StandardCharsets.US_ASCII),
ENVELOPE,
"application/json",
sha("1"),
Sha256.of(ENVELOPE),
sha("3"),
sha("4"),
"catalog-r1",
"binding-r1");
}
/** The row {@link OutboxStoreAdapter#append} writes for {@link #event}, still PENDING. */
private OutboxEventEntity pendingEntity(String eventId, String aggregateId) {
ArgumentCaptor<OutboxEventEntity> saved = forClass(OutboxEventEntity.class);
OutboxEventJpaRepository capture = mock(OutboxEventJpaRepository.class);
new OutboxStoreAdapter(capture, claimRepo).append(event(eventId, aggregateId));
verify(capture).save(saved.capture());
return saved.getValue();
}
private static Sha256 sha(String nibble) {
return new Sha256(HexFormat.of().parseHex(nibble.repeat(64)));
}
}
@@ -1,4 +1,4 @@
package dev.caskeleton.adapter.outbound.persistence.outbox;
package dev.caskeleton.adapter.outbound.persistence.outbox.jpa;
import static org.assertj.core.api.Assertions.assertThat;
@@ -24,6 +24,7 @@ c5f9c638c6d5b7768e803a23b3f16e9e0a5e09918c0838ed9c81cb6d9524ec9c jpa/notificati
1a5983c9212d6c155f0d7bea802bd9cd9c1055f3f0b055ba4168601146eeac0d postgresql/V16__outbox_canonical_hash_columns_varchar.sql
b8f571e6cada72a8f2776f4462509ce4b535c964c75b1c3cfb34b9dc07446d59 postgresql/V17__outbox_event_lease_fencing.sql
44cacbde7d1381ca5290fb8ec28005e8127ff6b453ff84277ec8d1b3293d76c8 postgresql/V18__outbox_event_unpublished_aggregate_order.sql
a0306e5b0fbcaf43984d256362dc4244aec57a0ce5031e4f5263be3762fe1caf postgresql/V19__outbox_event_canonical_only.sql
8ab106731d4d04d3719da0692069947736dc490ca46aa5a3ea9bdf65a5d956dc postgresql/V1__idempotency_record.sql
6b62a01a4eeb792b81015b4810ecc6f3f021e0a17dea50c871493f7694d4f0b9 postgresql/V3__outbox_event.sql
c57ab8a35a10079190ad8a563be58fae4147c9406c5bb752debb6998324ccdf6 postgresql/V4__int_lock.sql
+5
View File
@@ -15,6 +15,11 @@ Package roots: `dev.caskeleton.adapter.outbound` and
- Own reusable outbound correlation, fail-open dependency logging, and auto-configuration seams.
- Provide technical support used by registered messaging/cache/notification/httpclient leaves.
- Own the template's `IntegrationEventEncoderPort` (`messaging/JsonIntegrationEventEncoder`,
registered by `IntegrationEventEncoderAutoConfiguration` over every contract contribution bean,
backing off to a service's own encoder). It lives here because a use case encodes before it
appends to the outbox, in compositions that carry no messaging module; it is the application's
own envelope v1 format, not an external-system protocol.
- Keep feature-specific clients and routing policies in their owning leaf.
## Boundaries
+26
View File
@@ -38,6 +38,32 @@ component scan 없이 이 모듈이 있으면 등록된다). 네 기술 모듈
`@ConditionalOnProperty` 게이팅도 갖지 않는다 — 게이팅은 각 기술 모듈이 자신의 연동 client
단위로 소유한다.
## messaging — 템플릿의 integration event encoder
`JsonIntegrationEventEncoder`가 `IntegrationEventEncoderPort`의 템플릿 구현이다(소유자 결정 7:
outbox append는 canonical 하나, encoder는 템플릿이 준다). `IntegrationEventEncoderAutoConfiguration`이
context의 모든 `IntegrationEventContractContribution` bean으로 닫힌 catalog를 만들고, 서비스가 자기
encoder bean을 두면 물러난다.
- 형식: `shared-contract`의 envelope v1(`contracts/messaging/envelope/v1.schema.json`) 안에 payload
record를 `CanonicalJson`으로 한 번 렌더링해 넣는다. 한 값에는 렌더링이 하나다: component 선언
순서, 공백 없음, RFC 8259 필수 escape만, 숫자는 plain decimal. 그래서 envelope hash가 event를
대표한다.
- 받는 component 타입은 닫혀 있다: String, 정수형, BigDecimal, Boolean, enum, Instant, LocalDate,
UUID, Optional, List, public record. `double`/`float`는 거부한다(한 값에 철자가 여럿이라서). `null`도
거부한다 — 없을 수 있는 값은 Optional로 선언한다.
- 시작할 때 확인하는 것: payload 타입이 `IntegrationPayload`를 구현한 record인지, 선언한 component
순서가 record의 것인지, 선언한 schema hash가 classpath schema 파일 bytes의 SHA-256인지. schema를
고치고 hash를 안 고치면 기동이 실패한다.
- 확인하지 않는 것: payload를 JSON Schema로 검증하지 않는다(NetworkNT를 production에 다시 싣지
않았다). 매 event마다 검증하려는 서비스는 자기 encoder bean을 둔다.
- partition key는 tenant·logical destination·aggregate type·aggregate id의 domain-separated SHA-256이라
한 aggregate의 event는 한 partition으로 간다.
여기 있는 이유: use case가 append 전에 encode하므로 outbox를 쓰는 모든 조립에 있어야 한다.
messaging 모듈은 발행 쪽에만 있고(sample은 messaging이 없다), persistence는 직렬화를 소유하지
않는다. support는 outbound 어댑터가 있는 모든 조립에 있다.
## startup — 시작 실패 계약과 모듈 기본 설정 (app-bootstrap에서 이동)
capability 모듈이 합성 루트에 의존하지 않고 같은 방식으로 실패하고, 자기 설정을 가져오게 하려고
@@ -1,11 +1,18 @@
package dev.caskeleton.adapter.outbound.support;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.bind.PropertySourcesPlaceholdersResolver;
import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.core.env.Environment;
/**
@@ -79,4 +86,39 @@ public final class StrictSettingsBinder {
new CapabilityStartupValidationException(
prefix + " could not be bound although the capability is enabled"));
}
/**
* Binds the prefix strictly, except for keys under it that another module owns.
*
* <p>For a prefix two modules share: the idempotency lifecycle policy and the Redis store's own
* tuning both live under {@code ca-skeleton.capabilities.idempotency}. Each owner names what is
* not its own, rather than the check being dropped for the whole prefix — a misspelt lifecycle
* key is still refused.
*
* @param environment the environment to bind from
* @param prefix the settings prefix
* @param type the settings type
* @param foreignKeys keys relative to {@code prefix} (e.g. {@code key-version}) that another
* module binds
* @param <T> the settings type
* @return the bound settings
*/
public static <T> T bindExcept(
Environment environment, String prefix, Class<T> type, Set<String> foreignKeys) {
Set<ConfigurationPropertyName> foreign =
foreignKeys.stream()
.map(key -> ConfigurationPropertyName.of(prefix + "." + key))
.collect(Collectors.toUnmodifiableSet());
List<ConfigurationPropertySource> sources =
StreamSupport.stream(ConfigurationPropertySources.get(environment).spliterator(), false)
.map(source -> source.filter(name -> !foreign.contains(name)))
.toList();
BindHandler strict = new NoUnboundElementsBindHandler(BindHandler.DEFAULT);
return new Binder(sources, new PropertySourcesPlaceholdersResolver(environment))
.bind(prefix, Bindable.of(type), strict)
.orElseThrow(
() ->
new CapabilityStartupValidationException(
prefix + " could not be bound although the capability is enabled"));
}
}
@@ -0,0 +1,195 @@
package dev.caskeleton.adapter.outbound.support.messaging;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.lang.reflect.RecordComponent;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
/**
* Deterministic JSON for an integration-event payload record.
*
* <p>One value has exactly one rendering: record components in declaration order, no whitespace,
* the RFC 8259 mandatory escapes and nothing else, numbers in their plain decimal form. That is
* what lets the envelope hash stand for the event — two encodings of the same payload are the same
* bytes, so a republished row cannot drift from the one that was validated.
*
* <p>The accepted component types are closed. A floating-point value is refused rather than
* rendered, because {@code 0.1} has more than one faithful decimal spelling; a payload that needs a
* fraction declares {@link BigDecimal}. {@code null} is refused as well: an absent value is an
* {@link Optional}, so the schema, not the encoder, decides whether a field may be missing.
*/
final class CanonicalJson {
static final int MAXIMUM_DEPTH = 16;
static final int MAXIMUM_OBJECT_PROPERTIES = 64;
static final int MAXIMUM_ARRAY_ITEMS = 1024;
private CanonicalJson() {}
/** Renders a payload record as UTF-8 JSON bytes. */
static byte[] payload(Record payload) {
StringBuilder out = new StringBuilder(128);
writeRecord(out, payload, 1);
return strictUtf8(out);
}
/** Renders a JSON string literal, quotes included. */
static void writeString(StringBuilder out, String value) {
out.append('"');
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
switch (c) {
case '"' -> out.append("\\\"");
case '\\' -> out.append("\\\\");
case '\b' -> out.append("\\b");
case '\f' -> out.append("\\f");
case '\n' -> out.append("\\n");
case '\r' -> out.append("\\r");
case '\t' -> out.append("\\t");
default -> {
if (c < 0x20) {
out.append(String.format("\\u%04x", (int) c));
} else {
out.append(c);
}
}
}
}
out.append('"');
}
/** Encodes as UTF-8, refusing an unpaired surrogate instead of replacing it with {@code ?}. */
static byte[] strictUtf8(CharSequence text) {
try {
ByteBuffer encoded =
StandardCharsets.UTF_8
.newEncoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.encode(CharBuffer.wrap(text));
byte[] bytes = new byte[encoded.remaining()];
encoded.get(bytes);
return bytes;
} catch (CharacterCodingException exception) {
throw new IllegalArgumentException(
"integration event text contains an unpaired surrogate", exception);
}
}
private static void writeRecord(StringBuilder out, Record value, int depth) {
requireDepth(depth);
Class<?> type = value.getClass();
if (!Modifier.isPublic(type.getModifiers())) {
throw new IllegalArgumentException(
"payload record " + type.getName() + " must be public so its components can be read");
}
RecordComponent[] components = type.getRecordComponents();
if (components.length > MAXIMUM_OBJECT_PROPERTIES) {
throw new IllegalArgumentException(
"payload record " + type.getName() + " has more than 64 components");
}
out.append('{');
for (int i = 0; i < components.length; i++) {
if (i > 0) {
out.append(',');
}
writeString(out, components[i].getName());
out.append(':');
writeValue(out, read(components[i], value), depth + 1);
}
out.append('}');
}
private static Object read(RecordComponent component, Record value) {
try {
return component.getAccessor().invoke(value);
} catch (IllegalAccessException exception) {
throw new IllegalArgumentException(
"payload component " + component.getName() + " is not readable", exception);
} catch (InvocationTargetException exception) {
throw new IllegalArgumentException(
"payload component " + component.getName() + " failed when read", exception.getCause());
}
}
private static void writeValue(StringBuilder out, Object value, int depth) {
requireDepth(depth);
if (value == null) {
throw new IllegalArgumentException(
"payload values must not be null; declare an Optional component for an absent value");
}
if (value instanceof String text) {
writeString(out, text);
} else if (value instanceof Boolean flag) {
out.append(flag.booleanValue());
} else if (value instanceof Integer
|| value instanceof Long
|| value instanceof Short
|| value instanceof Byte
|| value instanceof BigInteger) {
out.append(value);
} else if (value instanceof BigDecimal decimal) {
BigDecimal stripped = decimal.stripTrailingZeros();
out.append((stripped.scale() < 0 ? stripped.setScale(0) : stripped).toPlainString());
} else if (value instanceof Enum<?> constant) {
writeString(out, constant.name());
} else if (value instanceof Instant instant) {
writeString(out, instant.toString());
} else if (value instanceof LocalDate date) {
writeString(out, date.toString());
} else if (value instanceof UUID uuid) {
writeString(out, uuid.toString());
} else if (value instanceof Optional<?> optional) {
if (optional.isPresent()) {
writeValue(out, optional.get(), depth);
} else {
out.append("null");
}
} else if (value instanceof List<?> list) {
writeList(out, list, depth);
} else if (value instanceof Record nested) {
writeRecord(out, nested, depth);
} else {
throw new IllegalArgumentException(
"payload component type "
+ value.getClass().getName()
+ " has no canonical JSON form; use String, a whole number, BigDecimal, Boolean,"
+ " an enum, Instant, LocalDate, UUID, Optional, List or a public record");
}
}
private static void writeList(StringBuilder out, List<?> list, int depth) {
// Copied first: a list that changes while it is written would be encoded as a value it never
// held, and the hash would then vouch for it.
List<?> snapshot = new ArrayList<>(list);
if (snapshot.size() > MAXIMUM_ARRAY_ITEMS) {
throw new IllegalArgumentException("payload list has more than 1024 items");
}
out.append('[');
for (int i = 0; i < snapshot.size(); i++) {
if (i > 0) {
out.append(',');
}
writeValue(out, snapshot.get(i), depth + 1);
}
out.append(']');
}
private static void requireDepth(int depth) {
if (depth > MAXIMUM_DEPTH) {
throw new IllegalArgumentException("payload nests deeper than 16 levels");
}
}
}
@@ -0,0 +1,31 @@
package dev.caskeleton.adapter.outbound.support.messaging;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
/**
* Provides the template's {@link IntegrationEventEncoderPort} over every contract contribution the
* application registers as a bean.
*
* <p>Here rather than in a messaging or persistence module because both sides of the outbox need it
* and neither owns the other: a use case encodes before it appends, and the append port and the
* publish bridge live in different modules. Every composition that has an outbound adapter has this
* module, so the encoder is there wherever an event can be written.
*
* <p>A service that supplies its own encoder bean — one that validates payloads against their JSON
* Schema, say — replaces this one.
*/
@AutoConfiguration
public class IntegrationEventEncoderAutoConfiguration {
@Bean
@ConditionalOnMissingBean(IntegrationEventEncoderPort.class)
public IntegrationEventEncoderPort integrationEventEncoder(
ObjectProvider<IntegrationEventContractContribution<?>> contributions) {
return new JsonIntegrationEventEncoder(contributions.orderedStream().toList());
}
}
@@ -0,0 +1,332 @@
package dev.caskeleton.adapter.outbound.support.messaging;
import dev.caskeleton.application.messaging.contract.ContractDescriptor;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
import dev.caskeleton.application.messaging.contract.Sha256;
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.RecordComponent;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
/**
* The template's {@link IntegrationEventEncoderPort}: JSON envelope v1 around a deterministic JSON
* rendering of the payload record.
*
* <p>The catalog is closed. It is the contract contributions given at construction and nothing
* else, and each one is checked then, not at the first event: the payload type is a public record
* implementing {@link IntegrationPayload}, the declared component order is the record's, and the
* declared payload schema hash is the SHA-256 of the schema bytes on the classpath. A contribution
* whose schema file was edited without its hash fails startup instead of stamping every event with
* a hash of a schema that no longer exists.
*
* <p>What this encoder does not do is validate the payload against its JSON Schema. The record type
* is the contract the application compiles against, and the schema file is its published
* description; a service that wants the two cross-checked on every event supplies its own encoder
* bean, and this one backs off.
*
* <p>The envelope shape is {@code contracts/messaging/envelope/v1.schema.json} (shared-contract),
* and its hash is taken from those bytes. The partition key is the domain-separated v1 derivation
* over tenant, logical destination, aggregate type and aggregate id, so every event of one
* aggregate lands on one partition.
*/
public final class JsonIntegrationEventEncoder implements IntegrationEventEncoderPort {
/** The shared envelope schema whose bytes this encoder's output conforms to. */
public static final String ENVELOPE_SCHEMA_RESOURCE =
"contracts/messaging/envelope/v1.schema.json";
/** The media type of every envelope this encoder writes. */
public static final String CONTENT_TYPE = "application/json";
private static final int ENVELOPE_VERSION = 1;
private static final byte[] SCHEMA_SET_DOMAIN = utf8("ca-skeleton.messaging.schema-set.v1");
private static final byte[] CATALOG_DOMAIN = utf8("ca-skeleton.messaging.contract-catalog.v1");
private static final byte[] DESCRIPTOR_DOMAIN =
utf8("ca-skeleton.messaging.contract-descriptor.v1");
private static final byte[] PARTITION_KEY_DOMAIN = utf8("ca-skeleton.messaging.partition-key.v1");
private static final byte[] PAYLOAD_PROPERTY = utf8(",\"payload\":");
private final Map<String, Entry> entries;
private final Sha256 envelopeSchemaHash;
private final String catalogRevision;
/**
* An encoder for exactly these contracts.
*
* @param contributions the closed contract catalog; may be empty, in which case every draft is
* refused as unknown
* @throws IllegalArgumentException when a contribution is malformed, duplicated or declares a
* schema hash that its classpath resource does not have
*/
public JsonIntegrationEventEncoder(
Collection<? extends IntegrationEventContractContribution<?>> contributions) {
if (contributions == null) {
throw new IllegalArgumentException("contract contributions must not be null");
}
this.envelopeSchemaHash =
resourceHash(JsonIntegrationEventEncoder.class.getClassLoader(), ENVELOPE_SCHEMA_RESOURCE);
Map<String, Entry> indexed = new HashMap<>();
for (IntegrationEventContractContribution<?> contribution : contributions) {
Entry entry = entryFor(contribution);
if (indexed.putIfAbsent(entry.key(), entry) != null) {
throw new IllegalArgumentException("duplicate integration event contract " + entry.key());
}
}
this.entries = Map.copyOf(indexed);
this.catalogRevision = catalogRevision(indexed.values());
}
@Override
public ValidatedIntegrationEvent encode(IntegrationEventDraft<?> draft) {
if (draft == null) {
throw new IllegalArgumentException("integration event draft must not be null");
}
String key = key(draft.contractId().value(), draft.payloadVersion());
Entry entry = entries.get(key);
if (entry == null) {
throw new IllegalArgumentException("no integration event contract is registered for " + key);
}
ContractDescriptor descriptor = entry.contribution().descriptor();
if (!draft.destinationId().equals(descriptor.logicalDestination())) {
throw new IllegalArgumentException(
"draft destination "
+ draft.destinationId().value()
+ " is not the destination contract "
+ key
+ " declares");
}
IntegrationPayload payload = draft.featurePayload();
if (payload.getClass() != entry.contribution().exactPayloadRecordType()) {
throw new IllegalArgumentException(
"draft payload must be exactly " + entry.contribution().exactPayloadRecordType());
}
byte[] payloadBytes = CanonicalJson.payload((Record) payload);
if (payloadBytes.length > descriptor.maximumPayloadBytes()) {
throw new IllegalArgumentException(
"payload of " + key + " exceeds " + descriptor.maximumPayloadBytes() + " bytes");
}
byte[] envelopeBytes = envelope(draft, payloadBytes);
if (envelopeBytes.length > descriptor.maximumEnvelopeBytes()) {
throw new IllegalArgumentException(
"envelope of " + key + " exceeds " + descriptor.maximumEnvelopeBytes() + " bytes");
}
String partitionKey = partitionKey(draft);
return new ValidatedIntegrationEvent(
draft.eventId(),
draft.contractId(),
ENVELOPE_VERSION,
draft.payloadVersion(),
draft.destinationId(),
draft.aggregate(),
draft.order(),
draft.occurredAt(),
draft.correlationId(),
draft.causationId(),
partitionKey,
partitionKey.getBytes(StandardCharsets.US_ASCII),
envelopeBytes,
CONTENT_TYPE,
entry.schemaSetHash(),
Sha256.of(envelopeBytes),
envelopeSchemaHash,
entry.contribution().payloadSchemaHash(),
catalogRevision,
entry.descriptorRevision());
}
private Entry entryFor(IntegrationEventContractContribution<?> contribution) {
if (contribution == null) {
throw new IllegalArgumentException("contract contribution must not be null");
}
if (contribution.contractId() == null || contribution.payloadVersion() <= 0) {
throw new IllegalArgumentException(
"contract contribution needs a contract id and a positive payload version");
}
String key = key(contribution.contractId().value(), contribution.payloadVersion());
Class<?> type = contribution.exactPayloadRecordType();
if (type == null || !type.isRecord() || !IntegrationPayload.class.isAssignableFrom(type)) {
throw new IllegalArgumentException(
key + " payload type must be a record implementing IntegrationPayload");
}
List<String> declared =
Arrays.stream(type.getRecordComponents()).map(RecordComponent::getName).toList();
if (!declared.equals(contribution.canonicalRecordComponentOrder())) {
throw new IllegalArgumentException(
key
+ " declares component order "
+ contribution.canonicalRecordComponentOrder()
+ " but "
+ type.getName()
+ " declares "
+ declared);
}
if (contribution.descriptor() == null
|| contribution.payloadSchemaResource() == null
|| contribution.payloadSchemaHash() == null) {
throw new IllegalArgumentException(key + " needs a descriptor and a payload schema identity");
}
Sha256 onClasspath =
resourceHash(type.getClassLoader(), contribution.payloadSchemaResource().value());
if (!onClasspath.equals(contribution.payloadSchemaHash())) {
throw new IllegalArgumentException(
key
+ " declares payload schema hash "
+ contribution.payloadSchemaHash()
+ " but "
+ contribution.payloadSchemaResource().value()
+ " hashes to "
+ onClasspath);
}
return new Entry(
key,
contribution,
schemaSetHash(envelopeSchemaHash, onClasspath),
descriptorRevision(contribution.descriptor()));
}
private static byte[] envelope(IntegrationEventDraft<?> draft, byte[] payloadBytes) {
StringBuilder metadata = new StringBuilder(256);
metadata.append("{\"envelopeVersion\":").append(ENVELOPE_VERSION);
property(metadata, "eventId", draft.eventId().value());
property(metadata, "contractId", draft.contractId().value());
metadata.append(",\"payloadVersion\":").append(draft.payloadVersion());
property(metadata, "logicalDestination", draft.destinationId().value());
metadata.append(",\"aggregate\":{\"type\":");
CanonicalJson.writeString(metadata, draft.aggregate().aggregateType());
metadata.append(",\"id\":");
CanonicalJson.writeString(metadata, draft.aggregate().aggregateId());
metadata.append(",\"sequence\":").append(draft.order().sequence());
metadata.append(",\"eventIndex\":").append(draft.order().eventIndex()).append('}');
property(metadata, "occurredAt", draft.occurredAt().toString());
property(metadata, "correlationId", draft.correlationId());
property(metadata, "contentType", CONTENT_TYPE);
byte[] head = CanonicalJson.strictUtf8(metadata);
// The payload is embedded as the exact bytes rendered once above, never re-rendered, so the
// bytes the size check measured are the bytes the envelope carries.
byte[] envelope = new byte[head.length + PAYLOAD_PROPERTY.length + payloadBytes.length + 1];
System.arraycopy(head, 0, envelope, 0, head.length);
System.arraycopy(PAYLOAD_PROPERTY, 0, envelope, head.length, PAYLOAD_PROPERTY.length);
System.arraycopy(
payloadBytes, 0, envelope, head.length + PAYLOAD_PROPERTY.length, payloadBytes.length);
envelope[envelope.length - 1] = (byte) '}';
return envelope;
}
private static void property(StringBuilder out, String name, String value) {
out.append(",\"").append(name).append("\":");
CanonicalJson.writeString(out, value);
}
private static String partitionKey(IntegrationEventDraft<?> draft) {
MessageDigest digest = sha256();
digest.update(PARTITION_KEY_DOMAIN);
digest.update((byte) 0);
lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.aggregate().tenantScope()));
lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.destinationId().value()));
lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.aggregate().aggregateType()));
lengthPrefixed(digest, CanonicalJson.strictUtf8(draft.aggregate().aggregateId()));
return HexFormat.of().formatHex(digest.digest());
}
private static Sha256 schemaSetHash(Sha256 envelope, Sha256 payload) {
MessageDigest digest = sha256();
digest.update(SCHEMA_SET_DOMAIN);
digest.update((byte) 0);
lengthPrefixed(digest, envelope.bytes());
lengthPrefixed(digest, payload.bytes());
return new Sha256(digest.digest());
}
/**
* The revision of how a contract is delivered: its destination and the limits and ordering it
* declares. Stamped on every event, so a consumer can tell events written under different
* delivery descriptors apart without the template owning a separate binding registry.
*/
private static String descriptorRevision(ContractDescriptor descriptor) {
MessageDigest digest = sha256();
digest.update(DESCRIPTOR_DOMAIN);
digest.update((byte) 0);
lengthPrefixed(digest, utf8(descriptor.ownerModule()));
lengthPrefixed(digest, utf8(descriptor.logicalDestination().value()));
lengthPrefixed(digest, utf8(descriptor.serializerId()));
lengthPrefixed(digest, utf8(Boolean.toString(descriptor.orderingRequired())));
lengthPrefixed(digest, utf8(Integer.toString(descriptor.maximumPayloadBytes())));
lengthPrefixed(digest, utf8(Integer.toString(descriptor.maximumEnvelopeBytes())));
lengthPrefixed(digest, utf8(descriptor.sensitivityClassification().name()));
lengthPrefixed(digest, utf8(descriptor.sameEventRequeueHorizon().toString()));
return HexFormat.of().formatHex(digest.digest());
}
/** The revision of the whole catalog: every contract, in a fixed order, with its schema hash. */
private static String catalogRevision(Collection<Entry> entries) {
List<Entry> ordered = new ArrayList<>(entries);
ordered.sort(Comparator.comparing(Entry::key));
MessageDigest digest = sha256();
digest.update(CATALOG_DOMAIN);
digest.update((byte) 0);
for (Entry entry : ordered) {
lengthPrefixed(digest, utf8(entry.key()));
lengthPrefixed(digest, entry.contribution().payloadSchemaHash().bytes());
lengthPrefixed(digest, utf8(entry.descriptorRevision()));
}
return HexFormat.of().formatHex(digest.digest());
}
private static Sha256 resourceHash(ClassLoader loader, String resource) {
ClassLoader effective = loader == null ? ClassLoader.getSystemClassLoader() : loader;
try (InputStream in = effective.getResourceAsStream(resource)) {
if (in == null) {
throw new IllegalArgumentException(
"schema resource " + resource + " is not on the classpath");
}
return Sha256.of(in.readAllBytes());
} catch (IOException exception) {
throw new IllegalArgumentException(
"schema resource " + resource + " is unreadable", exception);
}
}
private static void lengthPrefixed(MessageDigest digest, byte[] value) {
digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array());
digest.update(value);
}
private static MessageDigest sha256() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException("Java runtime does not provide SHA-256", exception);
}
}
private static String key(String contractId, int payloadVersion) {
return contractId + ":v" + payloadVersion;
}
private static byte[] utf8(String value) {
return value.getBytes(StandardCharsets.UTF_8);
}
private record Entry(
String key,
IntegrationEventContractContribution<?> contribution,
Sha256 schemaSetHash,
String descriptorRevision) {}
}
@@ -1 +1,2 @@
dev.caskeleton.adapter.outbound.support.OutboundSupportConfig
dev.caskeleton.adapter.outbound.support.messaging.IntegrationEventEncoderAutoConfiguration
@@ -0,0 +1,70 @@
package dev.caskeleton.adapter.outbound.support;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.time.Duration;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.bind.BindException;
import org.springframework.mock.env.MockEnvironment;
class StrictSettingsBinderTest {
private static final String PREFIX = "sample.shared";
/** Settings that own one key of a shared prefix. */
public record LifecycleSettings(Duration lease) {}
@Test
void aKeyAnotherModuleOwnsIsLeftToThatModule() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty(PREFIX + ".lease", "30s")
.withProperty(PREFIX + ".key-version", "1");
// when
LifecycleSettings settings =
StrictSettingsBinder.bindExcept(
environment, PREFIX, LifecycleSettings.class, Set.of("key-version"));
// then
assertThat(settings).isEqualTo(new LifecycleSettings(Duration.ofSeconds(30)));
}
@Test
void aMisspeltKeyUnderTheSharedPrefixIsStillRefused() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty(PREFIX + ".lease", "30s")
.withProperty(PREFIX + ".leese", "31s");
// when
Throwable thrown =
catchThrowable(
() ->
StrictSettingsBinder.bindExcept(
environment, PREFIX, LifecycleSettings.class, Set.of("key-version")));
// then
assertThat(thrown).isInstanceOf(BindException.class).hasStackTraceContaining("leese");
}
@Test
void placeholdersAreResolvedLikeAnyOtherBinding() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty("LEASE_FROM_ENV", "45s")
.withProperty(PREFIX + ".lease", "${LEASE_FROM_ENV:30s}");
// when
LifecycleSettings settings =
StrictSettingsBinder.bindExcept(environment, PREFIX, LifecycleSettings.class, Set.of());
// then
assertThat(settings.lease()).isEqualTo(Duration.ofSeconds(45));
}
}
@@ -0,0 +1,47 @@
package dev.caskeleton.adapter.outbound.support.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.annotation.ImportCandidates;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class IntegrationEventEncoderAutoConfigurationTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(IntegrationEventEncoderAutoConfiguration.class));
@Test
void theModuleRegistersTheEncoderAutoConfiguration() {
assertThat(ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()))
.contains(IntegrationEventEncoderAutoConfiguration.class.getName());
}
@Test
void theTemplateEncoderIsProvidedWhenTheServiceBringsNone() {
runner.run(
context ->
assertThat(context.getBean(IntegrationEventEncoderPort.class))
.isInstanceOf(JsonIntegrationEventEncoder.class));
}
@Test
void aServiceEncoderReplacesTheTemplateOne() {
// given
IntegrationEventEncoderPort own =
draft -> {
throw new UnsupportedOperationException("service encoder");
};
// when & then
runner
.withBean(IntegrationEventEncoderPort.class, () -> own)
.run(
context ->
assertThat(context.getBean(IntegrationEventEncoderPort.class)).isSameAs(own));
}
}

Some files were not shown because too many files have changed in this diff Show More