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
+8 -11
View File
@@ -276,12 +276,9 @@ jobs:
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2
- uses: ./.github/actions/setup-gradle-java
- name: Inbox PostgreSQL contract
- name: Messaging outbox, inbox and admin-journal PostgreSQL contracts
working-directory: src
run: ./gradlew :messaging:messaging-inbox-jdbc-postgresql:integrationTest --stacktrace
- name: Outbox PostgreSQL contract
working-directory: src
run: ./gradlew :messaging:messaging-outbox-jdbc-postgresql:integrationTest --stacktrace
run: ./gradlew :messaging:messaging-reliability-jdbc-postgresql:integrationTest --stacktrace
- name: Messaging starter Kafka round trip
working-directory: src
run: ./gradlew :messaging:messaging-spring-boot-starter:integrationTest --stacktrace
@@ -309,15 +306,15 @@ jobs:
- name: Integer lock migration compatibility
working-directory: src
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlIntLockMigrationCompatibilityIntegrationTest --stacktrace
- name: Legacy outbox transactional append
- name: Outbox transactional append
working-directory: src
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlLegacyOutboxAppendTransactionalIntegrationTest --stacktrace
- name: Legacy outbox concurrent relay
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxAppendTransactionalIntegrationTest --stacktrace
- name: Outbox concurrent relay
working-directory: src
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlLegacyOutboxConcurrentRelayIntegrationTest --stacktrace
- name: Legacy outbox row lifecycle
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxConcurrentRelayIntegrationTest --stacktrace
- name: Outbox row lifecycle
working-directory: src
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlLegacyOutboxRowLifecycleIntegrationTest --stacktrace
run: ./gradlew :adapter:outbound:persistence-jpa:postgresqlOutboxRowLifecycleIntegrationTest --stacktrace
# The optional gRPC platform build declares one strict INTEGRATION lane —
# `grpc-operation-ledger-jpa:integrationTest`, which certifies the atomic
+2 -2
View File
@@ -74,8 +74,8 @@ own `*-api` leaves are its ports, its broker leaves are its adapters, its starte
root — and the messaging module review (`docs/reviews/2026-08-14-messaging-module-code-review.md`
MSG-023 §6.2) chose that layout deliberately over folding it into `adapter:outbound:*`. This
application reaches it through the application-owned anti-corruption bridge in
`adapter:outbound:messaging` (MSG-015). The canonical bridge exists; legacy outbox/realtime cutover
still has explicitly documented seams in `src/messaging/CLAUDE.md`.
`adapter:outbound:messaging` (MSG-015). The canonical bridge is the only path: the legacy outbox
append port and the legacy Kafka publishing seam were deleted (owner decision 7).
Never infer an individual leaf's Gradle path, allowed dependency, or test command from this table.
Read its `gradle_path` and `allowed_dependencies` from `src/config/architecture/modules.json`; runtime
@@ -12,8 +12,8 @@ dev.caskeleton.adapter.outbound.persistence.config.PersistenceVendorSettings
dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping
dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy
dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy
dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig
dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping
dev.caskeleton.adapter.outbound.persistence.security.DatabasePrivilegeReport
+12 -12
View File
@@ -79,7 +79,6 @@ dev.caskeleton.adapter.outbound.persistence.experimental.tenant.TenantId
dev.caskeleton.adapter.outbound.persistence.failure.PersistenceExceptionTranslator
dev.caskeleton.adapter.outbound.persistence.failure.SqlStateErrorMapping
dev.caskeleton.adapter.outbound.persistence.failure.StandardSqlStateErrorMapping
dev.caskeleton.adapter.outbound.persistence.h2.H2OutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.h2.H2PersistenceConfig
dev.caskeleton.adapter.outbound.persistence.h2.H2SqlStateErrorMapping
dev.caskeleton.adapter.outbound.persistence.hibernate.HibernateProviderPolicy
@@ -100,9 +99,11 @@ dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.HibernateStatele
dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessRowCapExceededException
dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessWorkName
dev.caskeleton.adapter.outbound.persistence.hibernate.stateless.StatelessWorkResult
dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyReaper
dev.caskeleton.adapter.outbound.persistence.idempotency.IdempotencyRecordJpaRepository
dev.caskeleton.adapter.outbound.persistence.idempotency.entity.IdempotencyRecordEntity
dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyReaper
dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.IdempotencyRecordJpaRepository
dev.caskeleton.adapter.outbound.persistence.idempotency.jpa.entity.IdempotencyRecordEntity
dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.IdempotencySchemaStream
dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql.PostgreSqlOwnerSafeIdempotencyStore
dev.caskeleton.adapter.outbound.persistence.liveevent.JpaLiveEventReplayAdapter
dev.caskeleton.adapter.outbound.persistence.liveevent.LiveEventJpaRepository
dev.caskeleton.adapter.outbound.persistence.liveevent.entity.LiveEventEntity
@@ -165,12 +166,13 @@ dev.caskeleton.adapter.outbound.persistence.observation.SqlDiagnosticRedactor
dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationJpaRepository
dev.caskeleton.adapter.outbound.persistence.operation.DurableOperationStoreAdapter
dev.caskeleton.adapter.outbound.persistence.operation.entity.DurableOperationEntity
dev.caskeleton.adapter.outbound.persistence.outbox.OutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.outbox.OutboxEventJpaRepository
dev.caskeleton.adapter.outbound.persistence.outbox.OutboxReaper
dev.caskeleton.adapter.outbound.persistence.outbox.OutboxStoreAdapter
dev.caskeleton.adapter.outbound.persistence.outbox.entity.OutboxEventEntity
dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlOutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.outbox.h2.H2OutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxEventJpaRepository
dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxReaper
dev.caskeleton.adapter.outbound.persistence.outbox.jpa.OutboxStoreAdapter
dev.caskeleton.adapter.outbound.persistence.outbox.jpa.entity.OutboxEventEntity
dev.caskeleton.adapter.outbound.persistence.outbox.postgresql.PostgreSqlOutboxClaimRepository
dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlPersistenceConfig
dev.caskeleton.adapter.outbound.persistence.postgresql.PostgreSqlSqlStateErrorMapping
dev.caskeleton.adapter.outbound.persistence.postgresql.array.PostgreSqlArraySupport
@@ -188,8 +190,6 @@ dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlException
dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlFailureClassifier
dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlServerErrorFields
dev.caskeleton.adapter.outbound.persistence.postgresql.error.PostgreSqlState
dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.IdempotencySchemaStream
dev.caskeleton.adapter.outbound.persistence.postgresql.idempotency.PostgreSqlOwnerSafeIdempotencyStore
dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonDocument
dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonDocumentCodec
dev.caskeleton.adapter.outbound.persistence.postgresql.json.JsonPathName
+24
View File
@@ -422,3 +422,27 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap
| `GraphQlRequestEnvelopeValidator`·`GraphQlHttpRequestEnvelope` + `GraphQlRequestEnvelopeValidatorTest` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/` | `4fb7943b` | 요청 경로에서 도달 불가 (J-10d) |
| `MigrationFailedException`·`ProfileMismatchException`·`RequiredAdapterDisabledException`·`StartupValidationException` | `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/` | `f2857840^`(= `b7187e1b`) | 역할 없는 subclass (S6-#13) |
| `ExternalRequestUrlResolver`의 forwarded 파싱 + env `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | `src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java` | `d54909c4` | 컨테이너(RemoteIpValve)와 다른 두 번째 신뢰 판단 (I-5b) |
| `LegacyOutboxAppendPort` | `src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java` | `6d27356e` | canonical `OutboxAppendPort`로 통일(결정 7) |
| legacy outbox 모델 `NewOutboxEvent`, `OutboxEvent`, `CanonicalClaimedOutboxEvent`, `OutboxPayloadPolicy` (+ `NewOutboxEventTest`, `OutboxPayloadPolicyTest`) | `src/application-core/src/main/java/dev/caskeleton/application/outbox/` | `6d27356e` | append 모델이 `ValidatedIntegrationEvent` 하나. `ClaimedOutboxEvent`는 sealed 합집합이 아니라 canonical record |
| `LegacyOutboxAppendContract` | `src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/LegacyOutboxAppendContract.java` | `6d27356e` | `OutboxAppendContract`로 대체 |
| `CanonicalOutboxAppendAdapter` (+ Activation·단위 테스트) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java` | `6d27356e` | `OutboxStoreAdapter`가 `OutboxAppendPort`를 직접 구현(트랜잭션 guard 포함) |
| `OutboxEventEntity.payload`·`idempotencyKey` 접근자, claim SQL의 legacy CASE | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java`, `PostgreSqlOutboxClaimRepository`, `H2OutboxClaimRepository` | `6d27356e` | canonical 컬럼만 읽고 씀. 컬럼은 V19에서 nullable로 두고 migration은 수정하지 않음 |
| `OutboxCanonicalTransportRequirementValidator` (+ Validator/Composition 테스트) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java` | `6d27356e` | 켜고 끌 canonical 플래그가 없어짐 |
| 설정 키 `ca-skeleton.outbox.canonical-transport-enabled` / env `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` | `persistence-jpa.yml`, `docs/registries/env-keys.yaml`, `src/.env.example` | `6d27356e` | 같음 |
| messaging `core/*`: `MessageBroker`, `MessagePublisher`, `OutboundMessage`, `OutboundMessagePublisher`, `DisabledMessagePublisher` (+ `OutboundMessagePublisherTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/` | `6d27356e` | legacy 발행 경로 삭제. relay는 bridge(`IntegrationEventPublishPort`)만 씀 |
| `OutboxEnvelopeJson` (+ `OutboxCanonicalPublishRoutingTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java` | `6d27356e` | envelope은 encoder가 한 번 만들고 bytes 그대로 전달 |
| legacy Kafka seam: `KafkaSender`, `KafkaSenderAutoConfiguration`, `KafkaMessageBroker`, `KafkaAdapterConfig`, `KafkaAdapterSettings`, `BrokerAddress`, `LegacyKafkaMessagingRootAutoConfiguration`, `AutoConfiguration.imports` (+ 테스트 5개) | `src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/` | `6d27356e` | TLS/SASL 없는 두 번째 producer(X1-#1f, NEW-4a). leaf는 코드 없는 capability 묶음으로 유지 |
| `messaging.yml`의 `kafka.brokers` | `src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml` | `6d27356e` | seam 설정 |
| `WorkLogReservedIntegrationEvent`, `WorkLogReservedIntegrationEventMapper` (+ Mapper 테스트 2개) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/` | `6d27356e` | `PortfolioEventOutbox` + 계약 `portfolio.worklog.reserved` v1로 대체 |
| `SampleIdempotencyConfig` (executor 복사본) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java` | `6d27356e` | `composition:idempotency` 사용. Clock·스케줄링만 `SampleSchedulingConfig`로 |
| app-bootstrap `config/capabilities.yml` (이동) | `src/app-bootstrap/src/main/resources/config/capabilities.yml` | `6d27356e` | `composition/idempotency/.../config/module-defaults/idempotency.yml`로 이동 |
| app-bootstrap outbox 조립 `OutboxConfig`·`OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/` | `6d27356e` | `composition:outbox-relay`로 이동 |
| app-bootstrap 멱등성 조립 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/` | `6d27356e` | `composition:idempotency`로 이동 |
| app-bootstrap runtime 배선 tracing 6개, metrics 3개, `DomainContextConfig/Settings`, `PseudonymizationConfig`, `PrivacySettings`, `ManagementSecurityConfig` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/{autoconfigure/tracing,metrics,concurrency,logging,settings,management/security}/` | `6d27356e` | `composition:service-runtime`으로 이동 |
| sample bootstrap 복사본: `SampleTracingConfig`, `SampleTracingSettings`, `SampleTracingSampleRateResolver`(`staging` 분기), `SampleTracingSamplingEnvironmentPostProcessor`, `SampleMicrometerSpanErrorRecorder`, `SampleMetricsContractConfig`, `SampleDomainContextConfig`, `SamplePseudonymizationConfig`, `SamplePrivacySettings`, `META-INF/spring.factories` | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/{tracing,metrics,context,logging,settings}/` | `6d27356e` | 원본과 갈라진 복사본(S6-#7). 공용 모듈 사용 |
| messaging `OutboxRepository.leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous` | `src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java` | `6d27356e` | main 호출 0. fencing 없는 claim/쓰기 표면(S7-#8) |
| `JdbcOutboxRepository`의 LEASE SQL·`leaseBatch`·`*Unfenced` 4개·`update` helper·손 JSON(`toJson`/`fromJson`/`escape`/`unescape`) | `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java` | `6d27356e` | 호출 0. 손 JSON reader는 결함(P18-new-1). jsonb 함수로 대체 |
| leaf `messaging-outbox-jdbc-postgresql`, `messaging-inbox-jdbc-postgresql` (코드는 이동) | `src/messaging/messaging-outbox-jdbc-postgresql`, `src/messaging/messaging-inbox-jdbc-postgresql` | `6d27356e` | `messaging-reliability` + `messaging-reliability-jdbc-postgresql`로 재분할(S7-#5b) |
| application-core 테스트 `malformedReportData` | `src/application-core/src/test/java/dev/caskeleton/application/outbox/` (relay 테스트) | `6d27356e` | blank aggregate id를 가진 claim이 canonical 모델에서 만들어질 수 없음 |
| `EventJson`(sample 이벤트 JSON 문자열 조립, P15에서 신설) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/EventJson.java` | `25de288a` | P18 통합: sample 발행기가 canonical `PortfolioEventOutbox` + encoder로 옮겨 호출자 0 |
| `DomainContextSettings`(`ca-skeleton.domain-context.strategy`, P18이 service-runtime으로 옮긴 사본) | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/context/DomainContextSettings.java` | `e1dafd00`(P18 worktree) | P18 통합: P25 A-10c가 전략 선택 설정을 없앰 — `DomainContextConfig`가 `ThreadLocalDomainContextPropagator`를 직접 만든다 |
+8 -12
View File
@@ -21,20 +21,16 @@ Application의 canonical integration event를 platform publish pipeline으로
producing-service identity다.
값이 없으면 `IntegrationEventPublishPort` bridge 자체를 만들지 않는다. `spring.application.name`이나
현재 process 이름으로 추론하지 않는다. 기존 legacy `OutboxEvent`/realtime 경로는 별도 cutover가
끝날 때까지 `app.messaging.broker` 경로를 유지한다.
현재 process 이름으로 추론하지 않는다. 모든 발행(outbox relay 포함)이 이 bridge를 지나므로 messaging
모듈이 켜진 상태에서 값이 없으면 기동이 거부된다.
## Outbox canonical transport-only cutover
## Outbox
`APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` / `ca-skeleton.outbox.canonical-transport-enabled`은
기존 `outbox_event` writer/claim/status authority를 유지한 채 canonical row의 **transport만** platform
publish path로 보내는 compatibility gate다. 기본값은 `false`이며 두 번째 relay를 만들지 않는다.
`true`일 때는 `OutboxAppendPort`가 `ValidatedIntegrationEvent`의 exact envelope bytes와 canonical
metadata를 기존 outbox row에 저장하고, claim된 canonical row는 `IntegrationEventPublishPort`로 간다.
legacy row는 계속 `MessageBroker`를 사용한다. 따라서 mixed-row compatibility 기간에는 relay가 켜져
있다면 `app.messaging.broker`도 계속 필요하며, canonical path를 위해 `IntegrationEventPublishPort`도
추가로 필요하다. legacy backlog가 0이라는 별도 증거 없이 broker 요구를 제거하지 않는다.
outbox는 canonical 하나다(2026-09-28). use case가 `IntegrationEventEncoderPort`로 만든
`ValidatedIntegrationEvent`를 `OutboxAppendPort`로 append하고, relay는 claim한 row의 exact envelope
bytes를 `IntegrationEventPublishPort`로 보낸다. 예전의 `ca-skeleton.outbox.canonical-transport-enabled`
gate와 legacy `MessageBroker → KafkaSender` 경로는 삭제됐다. 발행할 contract의 logical destination마다
아래 destination profile을 선언한다(템플릿의 durable operation event는 `durable-operations`).
## Destination profile
+3 -3
View File
@@ -21,8 +21,8 @@ Flyway version `1000..1999`를 예약해서 애플리케이션의 일반적인
classpath:db/migration/messaging
```
현재 순서는 `V1001..V1005`(outbox/admin)와 `V1101`(inbox)이다. starter 테스트가 두 JDBC
모듈을 실제 combined classpath로 올려 version 중복과 예약 대역 이탈을 검사한다. 개별 DDL의
현재 순서는 `V1001..V1005`(outbox/admin)와 `V1101`(inbox)이고, 모두
`messaging-reliability-jdbc-postgresql`에 있다. starter 테스트가 그 모듈을 실제 combined classpath로 올려 version 중복과 예약 대역 이탈을 검사한다. 개별 DDL의
의미와 전환 순서는 [migration-guide.md](migration-guide.md)를 따른다.
## Outbox
@@ -39,7 +39,7 @@ COMMIT;
### relay
```text
leaseBatch(100, 30s) -- lease로 다중 relay 인스턴스 안전
claimBatch(owner, 100, 30s, now, maxAttempts) -- owner + fencing token으로 다중 relay 인스턴스 안전
→ publish (messageId 그대로)
→ CONFIRMED → markPublished
→ AMBIGUOUS → markAmbiguous (같은 messageId로 재시도 가능)
+4 -2
View File
@@ -17,8 +17,10 @@
> `BrokerFailureMatrix.shipped()` 하드코딩이 아니라 레인이 낸 증거(`BrokerCertificationEvidence`)에서
> 나온다. 증거가 없는 조합은 `NOT_COVERED`다 (MSG-014).
> **모듈 이름과 런타임 편입.** `messaging-outbox-jdbc-postgresql` / `messaging-inbox-jdbc-postgresql`은
> 이전에 `-jpa`로 불렸다. 구현은 Spring JDBC이고 SQL은 PostgreSQL 전용(`?::jsonb`,
> **모듈 이름과 런타임 편입.** 관계형 신뢰성 구현은 `messaging-reliability-jdbc-postgresql`,
> 그 port만 보는 relay·consumer 로직은 `messaging-reliability`다(2026-09-28에
> `messaging-outbox-jdbc-postgresql` / `messaging-inbox-jdbc-postgresql`을 이렇게 나눴다). 그 전에는
> `-jpa`로 불렸다. 구현은 Spring JDBC이고 SQL은 PostgreSQL 전용(`jsonb`,
> `FOR UPDATE SKIP LOCKED`, `ON CONFLICT`, `TIMESTAMPTZ`)이므로, 그 이름은 쓰지 않는 기술을
> 광고하고 vendor 중립 port(`messaging-reliability-api`)의 위치를 가렸다 (MSG-023).
>
+12 -23
View File
@@ -2913,8 +2913,9 @@ env_keys:
- name: APP_MESSAGING_BROKER
# source: messaging multi-broker redesign 2026-06-16 — single active broker selection
# (app.messaging.broker=<brokerId>); blank = messaging disabled. Replaces the former
# Kafka-binary APP_MESSAGING_KAFKA_ENABLED. Adding a broker is new files only.
# (app.messaging.broker=<brokerId>), read by the vendored messaging platform. Replaces the
# former Kafka-binary APP_MESSAGING_KAFKA_ENABLED. The application bridge no longer reads it:
# the legacy KafkaSender seam that did was removed with the canonical outbox (2026-09-28).
type: string
# The Kafka module's config/module-defaults/messaging.yml defaults it to kafka, the only registered broker.
default: kafka
@@ -2931,11 +2932,14 @@ env_keys:
# source: canonical messaging platform bridge 2026-09-18
# Explicit logical producing-service identity for IntegrationEventPublishPort.
# Blank/absent = canonical platform bridge is not exposed; identity is never inferred.
# Every publication, the outbox relay's included, goes through that bridge, so with the
# messaging module present and on a blank value refuses startup (2026-09-28 canonical outbox).
type: string
default: null
allowed_values: null
classification: public-config
required: false
required_when: APP_MESSAGING_ENABLED=true
reload_policy: restart-only
owner_branch: feature-integration-adapter-templates
validation: none
@@ -2945,9 +2949,9 @@ env_keys:
- name: APP_MESSAGING_KAFKA_BROKERS
# source: feature-domain-event-outbox-contract — "Kafka는 optional integration adapter"
# (broker 활성화 시 endpoint 필요)
# Also feeds app.messaging.brokers.kafka.bootstrap-servers (the messaging platform's Kafka
# transport) through the Kafka module's config/module-defaults/messaging.yml, so one key
# addresses both paths. spring.kafka.bootstrap-servers is not read.
# Feeds app.messaging.brokers.kafka.bootstrap-servers (the messaging platform's Kafka
# transport) through the Kafka module's config/module-defaults/messaging.yml.
# spring.kafka.bootstrap-servers is not read.
type: csv_list
default: null
allowed_values: null
@@ -4185,26 +4189,11 @@ env_keys:
validation: boolean
compatibility_impact: behavior-change
required_test: adapter-contract:outbox-capability-disabled-safe
- name: APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED
# source: MSG-015 transport-only cutover 2026-09-18
# Enables canonical outbox rows/platform transport without switching publication authority.
type: boolean
default: false
allowed_values:
- "true"
- "false"
classification: public-config
required: false
reload_policy: restart-only
owner_branch: feature-integration-adapter-templates
validation: boolean
compatibility_impact: additive
required_test: app-bootstrap:outbox-canonical-transport-gate
- name: APP_OUTBOX_RELAY_ENABLED
# source: five-adapter-runtime-remediation §6.3 MSG-INT-001 — starts the relay scheduler.
# Requires APP_OUTBOX_ENABLED, APP_PERSISTENCE_JPA_ENABLED and APP_MESSAGING_ENABLED with a
# broker; the shipped default was true beside a blank broker, which refused every startup.
# Requires APP_OUTBOX_ENABLED, APP_PERSISTENCE_JPA_ENABLED and APP_MESSAGING_ENABLED with
# APP_MESSAGING_PRODUCER_ID; the shipped default was true beside a blank broker, which refused
# every startup.
type: boolean
default: false
allowed_values: [true, false]
@@ -0,0 +1,90 @@
# W3-P18 — outbox canonical 통일 + `composition:*` + legacy Kafka seam 삭제
- worktree: `/home/donghyeon/workspace/chat-gpt-container/codebase/clean-architecture-backend-template/.claude/worktrees/agent-aabba563c6ef6bf7d`
- 브랜치: `worktree-agent-aabba563c6ef6bf7d` (기준 `016597ac`)
- 커밋(순서대로):
- `6268c494` P18 D: outbox를 canonical 하나로 통일하고 legacy Kafka 발행 경로 삭제
- `a053ae89` P18 W3: outbox relay·멱등성 executor 조립을 composition 모듈로 이동
- `910ab7ab` P18 W3: persistence-jpa outbox·멱등성 패키지를 feature 기준으로 이동
- `165e0499` P18 W3: messaging outbox 죽은 표면 삭제와 header JSON을 jsonb로
- `2ddd210a` P18 W3: sample 복사 bootstrap 인프라를 composition:service-runtime 공용 모듈로
- `e1dafd00` P18 W3: messaging outbox·inbox leaf를 reliability(stdlib)와 reliability-jdbc-postgresql로 재분할
- W1·W2 커밋은 따로 없다. W1 행 3개와 W2 행 2개는 D 커밋(`6268c494`)의 삭제와 sample 이전으로 닫혔다.
- 추가한 migration 버전: persistence-jpa `V19__outbox_event_canonical_only.sql`. `applied-migrations.sha256`에 한 줄을 더했다: `a0306e5b0fbcaf43984d256362dc4244aec57a0ce5031e4f5263be3762fe1caf postgresql/V19__outbox_event_canonical_only.sql`. 이미 적용된 migration은 고치지 않았다. messaging의 `V1001..V1005`·`V1101`은 내용을 바꾸지 않고 `messaging-reliability-jdbc-postgresql`로 옮기기만 했다. classpath 위치 `db/migration/messaging`도 같다.
- registry 변경:
- 추가: `composition-outbox-relay`, `composition-idempotency`, `composition-service-runtime`, `messaging-reliability`, `messaging-reliability-jdbc-postgresql`.
- 삭제: `messaging-outbox-jdbc-postgresql`, `messaging-inbox-jdbc-postgresql`.
- `adapter-outbound-messaging-kafka`는 registry에 남겼다. 코드가 없는 capability 묶음으로, bridge와 `messaging-spring-boot-starter-kafka`를 `runtimeOnly`로 싣는다. 한 줄 선택(`runtimeOnly project(':adapter:outbound:messaging-kafka')`)을 그대로 쓰기 위해서다.
- env 키 변경:
- `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` 삭제.
- `APP_MESSAGING_PRODUCER_ID`를 `required_when: APP_MESSAGING_ENABLED=true`로 바꿨다.
- `env-keys.yaml`, `.env.example`, `compose-profile-contracts.json`을 함께 고쳤다.
- 설정 prefix는 바꾸지 않았다(3-B 몫).
- `docs/capability-status.md`는 고치지 않았다. 아래 "제거된 코드" 표를 오케스트레이터가 옮겨 적어야 한다.
## 행 결과
| ID | 결과 | 근거 |
|---|---|---|
| X1-지도-Kafka producer | 해당 없음(코드 삭제) | **삭제:** legacy seam producer(`KafkaSenderAutoConfiguration`·`KafkaSender`·`LegacyKafkaMessagingRootAutoConfiguration`)를 `6268c494`에서 지웠다.<br>**남은 producer:** platform 하나다. `KafkaSecurityConfigurer`로 TLS/SASL을 적용한다: `src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java:188` `config.putAll(producerSecurity(...))`, `:216`.<br>**같은 결함 없음:** `MessagingSecuredBrokerQualificationTest`가 PASS다 — `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresSaslAsTheProviderUser`, `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresAClientCertificate`, `:messaging:messaging-spring-boot-starter:integrationTest` 3/3. |
| X1-#1f | 해당 없음(코드 삭제) | 위와 같다. 보안 블록을 추가할 대상인 `KafkaAdapterSettings`·`kafkaSeamProducer`가 `6268c494`에서 삭제됐다. canonical 경로의 producer는 `KafkaMessagingAutoConfiguration.java:188`에서 보안 profile을 적용하고, `MessagingSecuredBrokerQualificationTest` 2/2가 PASS다. |
| NEW-4a | 해당 없음(코드 삭제) | **삭제:** 항상 PLAINTEXT인 seam producer(`KafkaSenderAutoConfiguration.java:62-80`)와 그것을 켜던 `LegacyKafkaMessagingRootAutoConfiguration`이 `6268c494`에서 삭제됐다. messaging-kafka의 `AutoConfiguration.imports`도 삭제했다.<br>**남은 producer:** platform producer 하나다(`KafkaMessagingAutoConfiguration.java:188`, `:216`). 보안 profile이 없는데 broker가 TLS를 요구하면 기동을 거부하는 규칙도 그 경로에 그대로 있다.<br>**테스트:** `KafkaCapabilityActivationTest`는 leaf가 bridge+starter 묶음이 된 것에 맞게 갱신했고 PASS다. |
| S6-lead-3 | 완료 | **이전:** sample 3곳(`CreateWorkLogUseCase`, `PosterEventPublisher`, `PosterImagePublicationEventPublisher`)을 `PortfolioEventOutbox`로 옮겼다(`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java:44`). 이 클래스는 `OutboxAppendPort`와 `IntegrationEventEncoderPort`를 쓴다.<br>**계약 등록:** `PortfolioEventContracts`가 계약 8개(poster 7 + `portfolio.worklog.reserved` v1)와 schema hash를 등록한다.<br>**삭제:** `LegacyOutboxAppendPort`.<br>**테스트:** `PortfolioEventOutboxTest`, `PortfolioEventContractsTest`, `CreateWorkLogOutboxTest`, `PosterEventPublisherTest`, `WorkLogReservedConsumerDedupeContractTest` PASS. `:sample-portfolio:test` 289, integrationTest 49, systemTest 3, webSystemTest 5 모두 PASS. |
| S7-lead-3 | 해당 없음(코드 삭제) | R0 경로(`LegacyKafkaMessagingRootAutoConfiguration`·`KafkaSender`·`KafkaSenderAutoConfiguration`·`KafkaMessageBroker`)를 `6268c494`에서 삭제했다. 남은 Kafka producer는 platform `KafkaMessagingTransport` 하나다. |
| X1-지도-Outbox | 완료 | **append 포트:** `OutboxAppendPort` 하나다(`src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java:15`). `LegacyOutboxAppendPort`는 삭제했다.<br>**구현:** `OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort`(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java:48`). `CanonicalOutboxAppendAdapter`는 여기로 합쳤다.<br>**X1-#1c guard:** `append` 첫 줄의 `requireTransaction("append")`(`:65`)다.<br>**relay 조립:** `composition:outbox-relay`에 있다(`src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:53`).<br>**테스트:** `OutboxAppendContract`(application-core testFixtures)를 fake와 adapter가 공유한다. PostgreSQL lane `postgresqlOutboxAppendTransactionalIntegrationTest` 2, `postgresqlOutboxConcurrentRelayIntegrationTest` 4, `postgresqlOutboxRowLifecycleIntegrationTest` 10 PASS. |
| X1-#1b | 완료 | **소비자 4곳 이전:** `SubmitDurableOperationUseCase`(`src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java:72`, 계약 `DurableOperationSubmittedContract`)와 sample 3곳이 `OutboxAppendPort`를 쓴다.<br>**encoder:** 템플릿 encoder `JsonIntegrationEventEncoder`(`src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java:47`)와 `IntegrationEventEncoderAutoConfiguration`.<br>**테스트:** `JsonIntegrationEventEncoderTest`, `IntegrationEventEncoderAutoConfigurationTest`, `DurableOperationSubmissionOutboxIntegrationTest`(실제 encoder) PASS. |
| X1-#1i | 완료 | **이동:** `OutboxConfig`→`OutboxRelayAutoConfiguration`, 그리고 `OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken`을 `src/composition/outbox-relay`로 옮겼다(`a053ae89`).<br>**삭제:** `OutboxCanonicalTransportRequirementValidator`는 옮기지 않고 삭제했다. 켜고 끌 canonical 플래그가 더는 없다.<br>**연결:** app-bootstrap은 `runtimeOnly project(':composition:outbox-relay')` 한 줄로 받는다.<br>**테스트:** `OutboxRelayAutoConfigurationTest`(`aMisspeltOutboxKeyFailsStartupInsteadOfLeavingTheDefaultInForce` 포함), `OutboxRelaySchedulerLoggingTest` PASS. |
| S1-#2b / S2-#4b | 완료 | **application-core:** `ClaimedOutboxEvent`는 이제 sealed 합집합이 아니다. `record(ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount)`(`ClaimedOutboxEvent.java:19`)다.<br>**persistence-jpa:** legacy adapter와 entity의 `payload`·`idempotencyKey` 접근자를 삭제했다. canonical metadata가 불완전한 row는 claim할 때 DEAD가 된다. claim SQL(PG·H2)에서 legacy CASE를 없앴다.<br>**V19:** 미발행 pre-canonical row가 있으면 migration이 실패한다. CHECK `ck_outbox_event_canonical_unless_published`를 추가했다.<br>**테스트:** `PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.aRowWithoutTheCanonicalEnvelopeIsRefusedUnlessItIsPublished`·`aPublishedPreCanonicalRowIsKeptForTheReaper`·`theCanonicalOnlyMigrationRefusesADatabaseThatStillHoldsAnUndeliveredPreCanonicalRow` PASS(jpaPlatformContractTest 221, 이 클래스 9/9). `H2ClaimSqlTest`, `OutboxStoreAdapterTest` PASS. |
| S2-lead-1 | 완료 | 포트 버전이 하나로 줄었다: `OutboxAppendPort`(append)와 `OutboxStorePort`(claim/완료). 근거는 S1-#2b와 같다. |
| S7-#8 | 완료 | **삭제:** `OutboxRepository`의 `leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous`(`src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java:43`, `:57`만 남음). `JdbcOutboxRepository`의 LEASE SQL, `*Unfenced` 4개, `update` helper, 손으로 쓴 JSON(`toJson`/`fromJson`/`escape`/`unescape`).<br>**header 저장:** `jsonb_object(?::text[])`로 쓰고 `jsonb_each_text`로 읽는다(`src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java:59`, `:77-78`).<br>**TDD:** `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader`(`OutboxPostgresIT.java:612`)가 먼저 FAIL했다("map entries not expected: x-path=C:\exports\"") → 수정 후 PASS. integrationTest 36/36.<br>**그대로 둔 것:** purge 오버로드(1차 M-6)는 손대지 않았다. |
| S4-lead-4b | 완료 | **삭제:** `core/MessageBroker` 계열(MessageBroker, MessagePublisher, OutboundMessage, OutboundMessagePublisher, DisabledMessagePublisher)과 `OutboxEnvelopeJson`, `adapter:outbound:messaging-kafka`의 Java 코드 전부.<br>**relay 경로:** relay는 claim한 row의 `ValidatedIntegrationEvent`를 bridge로만 보낸다(`OutboxMessagePublishAdapter(IntegrationEventPublishPort)`, `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java:23`).<br>**leaf를 남긴 이유:** 계획은 leaf 삭제였다. 대신 bridge+starter-kafka를 싣는 코드 없는 capability 묶음으로 남겼다. 한 줄 선택이 유지되고, bridge leaf는 broker 중립으로 남는다.<br>**테스트:** `KafkaCapabilityActivationTest` PASS. |
| NEW-2a | 완료 | X1-#1i와 같다. 조립은 `src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:43-53`에 있고, app-bootstrap `AutoConfiguration.imports`에서 outbox 줄을 뺐다. |
| NEW-2b | 완료 | **이동:** `IdempotencyProviderSelectionConfig`→`IdempotencyAutoConfiguration`(`src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java:38`, executor 생성 `:58`).<br>**설정:** `IdempotencySettings.bind`는 `StrictSettingsBinder.bindExcept`로 strict 바인딩한다. `config/module-defaults/idempotency.yml`로 옮겼다(예전 `capabilities.yml`).<br>**sample:** `SampleIdempotencyConfig`를 삭제했다. Clock·`@EnableScheduling`만 `SampleSchedulingConfig`에 남겼다.<br>**테스트:** `IdempotencySettingsTest`(strict), `IdempotencyAutoConfigurationTest`, `IdempotencyModuleDefaultsTest`, `StrictSettingsBinderTest`, `SampleIdempotencyReplayIntegrationTest` PASS. |
| G-11b | 완료 | NEW-2b와 같다. `modules.json`에 `composition-idempotency`(edge application-core, adapter-outbound-support)를 등록했다. app-bootstrap과 sample이 `runtimeOnly project(':composition:idempotency')`를 쓴다. |
| X1-#2b | 완료 | executor 생성은 한 곳이다: `IdempotencyAutoConfiguration.java:58`. main에 `new IdempotencyExecutor`는 여기뿐이다. web testFixtures의 fault fixture는 테스트용이다. provider는 store bean만 기여한다. |
| S1-lead-3 | 완료 | NEW-2b와 같다. |
| X1-지도-요청 멱등성 | 완료 | 조립이 한 곳이다(`composition:idempotency`). 두 root가 같은 모듈을 쓴다. |
| S6-#7 | 완료 | **새 leaf `composition:service-runtime`**(`dev.caskeleton.composition.runtime`, edge application-core, shared-contract, adapter-outbound-support, adapter-outbound-identifier):<br>- 원본을 app-bootstrap에서 옮겼다: `tracing`(TracingConfig 외 5), `metrics`(MetricsContractConfig+filter 2), `context`(DomainContextConfig/Settings), `logging`(PseudonymizationConfig, PrivacySettings), `management/security`(ManagementSecurityConfig).<br>- 모두 이 모듈의 `AutoConfiguration.imports`로, sampling bridge는 `spring.factories`로 등록한다.<br>- app-bootstrap과 sample이 `runtimeOnly project(':composition:service-runtime')`를 쓴다.<br>**sample:** 복사본 10개와 `spring.factories`를 삭제했다. 원본을 쓰므로 `staging=0.10` 분기도 사라졌다.<br>**sample actuator chain:** 복사본이 아니라 공개 데모라는 샘플만의 결정이라 남겼다. bean 이름을 `actuatorSecurityFilterChain`으로 바꿔 공용 chain이 물러나게 했다(`ConditionalOnMissingBean(name)`).<br>**테스트:** `ServiceRuntimeRegistrationTest` 4개(신규), 옮긴 테스트 9 클래스 — `:composition:service-runtime:test` 86 PASS. `ActuatorSecurityHttpTest`, `DefaultCompositionBootTest`, `StartupOrderContractTest`, `ConfigurationNamespaceContractTest` 갱신 후 PASS. |
| S7-#5b | 완료 | **`messaging-reliability`**(stdlib: `OutboxRelay`·`OutboxRelayWorker`·`OutboxRetryScheduler`·`OutboxEnvelopeFactory`·`OutboxCleanupJob`·`OutboxProperties`·`OutboxRelayReport`, `IdempotentConsumer`·`TransactionalInboxHandler`·`InboxCleanupJob`·`InboxOutcome`·`InboxRetentionPolicy`).<br>**`messaging-reliability-jdbc-postgresql`**(`JdbcOutboxRepository`, `JdbcInboxRepository`, `JdbcAdminOperationJournal`, migration `V1001..V1005`·`V1101`, PG IT 3개).<br>**영향:** 옛 두 leaf는 삭제했다. 패키지명은 그대로라 starter 코드는 바뀌지 않았다. CI lane `integration-main.yml`을 새 경로로 바꿨다.<br>**테스트:** `:messaging:messaging-reliability:test` 47, `:messaging:messaging-reliability-jdbc-postgresql:test` 8, integrationTest 36, starter test 87, integrationTest 3 PASS. |
| S2-#9b | 완료 | 이동만 했다(`910ab7ab`). 새 패키지는 `persistence/outbox/{jpa(+entity),postgresql,h2}`, `persistence/idempotency/{jpa(+entity),postgresql}`다. JPA API surface는 `updateJpaApiSurface -PapproveJpaApiSurfaceChange`로 다시 승인했다. `JpaModuleBoundaryTest`에 autoconfigure→idempotency edge를 기록했다. `verifyJpaApiSurface`·`verifyJpaReadinessRegistry` PASS. |
## 제거된 코드
| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 |
|---|---|---|---|
| `LegacyOutboxAppendPort` | `src/application-core/src/main/java/dev/caskeleton/application/outbox/LegacyOutboxAppendPort.java` | `6d27356e` | canonical `OutboxAppendPort`로 통일(결정 7) |
| legacy outbox 모델 `NewOutboxEvent`, `OutboxEvent`, `CanonicalClaimedOutboxEvent`, `OutboxPayloadPolicy` (+ `NewOutboxEventTest`, `OutboxPayloadPolicyTest`) | `src/application-core/src/main/java/dev/caskeleton/application/outbox/` | `6d27356e` | append 모델이 `ValidatedIntegrationEvent` 하나. `ClaimedOutboxEvent`는 sealed 합집합이 아니라 canonical record |
| `LegacyOutboxAppendContract` | `src/application-core/src/testFixtures/java/dev/caskeleton/application/outbox/testkit/LegacyOutboxAppendContract.java` | `6d27356e` | `OutboxAppendContract`로 대체 |
| `CanonicalOutboxAppendAdapter` (+ Activation·단위 테스트) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/CanonicalOutboxAppendAdapter.java` | `6d27356e` | `OutboxStoreAdapter`가 `OutboxAppendPort`를 직접 구현(트랜잭션 guard 포함) |
| `OutboxEventEntity.payload`·`idempotencyKey` 접근자, claim SQL의 legacy CASE | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/entity/OutboxEventEntity.java`, `PostgreSqlOutboxClaimRepository`, `H2OutboxClaimRepository` | `6d27356e` | canonical 컬럼만 읽고 씀. 컬럼은 V19에서 nullable로 두고 migration은 수정하지 않음 |
| `OutboxCanonicalTransportRequirementValidator` (+ Validator/Composition 테스트) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxCanonicalTransportRequirementValidator.java` | `6d27356e` | 켜고 끌 canonical 플래그가 없어짐 |
| 설정 키 `ca-skeleton.outbox.canonical-transport-enabled` / env `APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED` | `persistence-jpa.yml`, `docs/registries/env-keys.yaml`, `src/.env.example` | `6d27356e` | 같음 |
| messaging `core/*`: `MessageBroker`, `MessagePublisher`, `OutboundMessage`, `OutboundMessagePublisher`, `DisabledMessagePublisher` (+ `OutboundMessagePublisherTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/core/` | `6d27356e` | legacy 발행 경로 삭제. relay는 bridge(`IntegrationEventPublishPort`)만 씀 |
| `OutboxEnvelopeJson` (+ `OutboxCanonicalPublishRoutingTest`) | `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxEnvelopeJson.java` | `6d27356e` | envelope은 encoder가 한 번 만들고 bytes 그대로 전달 |
| legacy Kafka seam: `KafkaSender`, `KafkaSenderAutoConfiguration`, `KafkaMessageBroker`, `KafkaAdapterConfig`, `KafkaAdapterSettings`, `BrokerAddress`, `LegacyKafkaMessagingRootAutoConfiguration`, `AutoConfiguration.imports` (+ 테스트 5개) | `src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/` | `6d27356e` | TLS/SASL 없는 두 번째 producer(X1-#1f, NEW-4a). leaf는 코드 없는 capability 묶음으로 유지 |
| `messaging.yml`의 `kafka.brokers` | `src/adapter/outbound/messaging-kafka/src/main/resources/config/module-defaults/messaging.yml` | `6d27356e` | seam 설정 |
| `WorkLogReservedIntegrationEvent`, `WorkLogReservedIntegrationEventMapper` (+ Mapper 테스트 2개) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/` | `6d27356e` | `PortfolioEventOutbox` + 계약 `portfolio.worklog.reserved` v1로 대체 |
| `SampleIdempotencyConfig` (executor 복사본) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java` | `6d27356e` | `composition:idempotency` 사용. Clock·스케줄링만 `SampleSchedulingConfig`로 |
| app-bootstrap `config/capabilities.yml` (이동) | `src/app-bootstrap/src/main/resources/config/capabilities.yml` | `6d27356e` | `composition/idempotency/.../config/module-defaults/idempotency.yml`로 이동 |
| app-bootstrap outbox 조립 `OutboxConfig`·`OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/` | `6d27356e` | `composition:outbox-relay`로 이동 |
| app-bootstrap 멱등성 조립 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/` | `6d27356e` | `composition:idempotency`로 이동 |
| app-bootstrap runtime 배선 tracing 6개, metrics 3개, `DomainContextConfig/Settings`, `PseudonymizationConfig`, `PrivacySettings`, `ManagementSecurityConfig` (이동) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/{autoconfigure/tracing,metrics,concurrency,logging,settings,management/security}/` | `6d27356e` | `composition:service-runtime`으로 이동 |
| sample bootstrap 복사본: `SampleTracingConfig`, `SampleTracingSettings`, `SampleTracingSampleRateResolver`(`staging` 분기), `SampleTracingSamplingEnvironmentPostProcessor`, `SampleMicrometerSpanErrorRecorder`, `SampleMetricsContractConfig`, `SampleDomainContextConfig`, `SamplePseudonymizationConfig`, `SamplePrivacySettings`, `META-INF/spring.factories` | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/{tracing,metrics,context,logging,settings}/` | `6d27356e` | 원본과 갈라진 복사본(S6-#7). 공용 모듈 사용 |
| messaging `OutboxRepository.leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous` | `src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java` | `6d27356e` | main 호출 0. fencing 없는 claim/쓰기 표면(S7-#8) |
| `JdbcOutboxRepository`의 LEASE SQL·`leaseBatch`·`*Unfenced` 4개·`update` helper·손 JSON(`toJson`/`fromJson`/`escape`/`unescape`) | `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java` | `6d27356e` | 호출 0. 손 JSON reader는 결함(P18-new-1). jsonb 함수로 대체 |
| leaf `messaging-outbox-jdbc-postgresql`, `messaging-inbox-jdbc-postgresql` (코드는 이동) | `src/messaging/messaging-outbox-jdbc-postgresql`, `src/messaging/messaging-inbox-jdbc-postgresql` | `6d27356e` | `messaging-reliability` + `messaging-reliability-jdbc-postgresql`로 재분할(S7-#5b) |
| application-core 테스트 `malformedReportData` | `src/application-core/src/test/java/dev/caskeleton/application/outbox/` (relay 테스트) | `6d27356e` | blank aggregate id를 가진 claim이 canonical 모델에서 만들어질 수 없음 |
## 새로 발견한 결함
- **P18-new-1** (고침): header를 두 방향이 다르게 escape했다.
- 위치: `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java`, 손으로 쓴 JSON reader(삭제 전 `:608-680`).
- 증상: escape된 backslash 뒤의 따옴표를 escape된 따옴표로 읽었다. 그래서 `\`로 끝나는 header 값이 다음 header를 삼키거나 값 끝에 `"`가 붙어 돌아왔다.
- 수정: PostgreSQL `jsonb_object(text[])`로 쓰고 `jsonb_each_text`로 읽는다(`165e0499`, 현재 `messaging-reliability-jdbc-postgresql/.../JdbcOutboxRepository.java:59`, `:77-78`).
- TDD: `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader`가 먼저 FAIL했고(`map entries not expected: x-path=C:\exports\"`), 수정 후 PASS.
- **P18-new-2** (안 고침): root `CLAUDE.md`의 문장 하나가 사실과 다르다.
- 위치: "Module families" 절, "The canonical bridge exists; legacy outbox/realtime cutover still has explicitly documented seams in `src/messaging/CLAUDE.md`".
- 이유: 이번 묶음에서 cutover가 끝났고, `src/messaging/CLAUDE.md`에는 남은 seam 기록이 없다.
- root 정책 문서(AGENTS.md 요약)라 손대지 않았다. 문장 삭제나 수정이 필요하다.
- **P18-new-3** (고침, 설계 노트): actuator chain의 켜짐 조건이 바뀌었다.
- 예전: app-bootstrap의 scan되는 `@Configuration`이었다. web security를 끈 좁은 slice에서도 `HttpSecurity`를 요구했다.
- 지금: auto-configuration이 되면서 `@ConditionalOnBean(HttpSecurity)` + `before = ServletWebSecurity/ManagementWebSecurity` 조건이 붙었다(`src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/management/security/ManagementSecurityConfig.java`).
- 앞으로의 동작: web security를 직접 켜지 않고 Boot의 자동 `@EnableWebSecurity`에만 기대는 조립은 이 chain 대신 Boot 기본 actuator chain(health 개방, 나머지 인증)을 받는다. 두 shipped root는 web adapter `SecurityConfig`(highest precedence)나 자기 chain으로 영향이 없다.
- `ActuatorSecurityHttpTest` slice는 `@EnableWebSecurity`를 명시하도록 고쳤다.
@@ -374,7 +374,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| G-10a | Consider | SCRIPT ACL probe가 `return {1}`이라 스크립트 내부 명령(`TIME`/`HSET`/`PEXPIRE`/`DEL`) 권한 부족을 기동 때 못 잡음 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): `RedisSemanticScriptAclProbe.java:29-38`: probe key에서 `TIME`→`HSET`→`PEXPIRE`→`HGET`→`DEL`을 실행하고 읽은 값이 쓴 값과 같을 때만 `{1}`. `anAccountDeniedACommandTheScriptsCallFailsStartup`[HSET/PEXPIRE/HGET/DEL] FAIL→PASS. 실제 Redis standalone·cluster에서 `LiveRedisSemanticScriptAclProbeTest` 2건 PASS. 테스트 ACL `+time`은 NEW-5a(W1)에서 추가 | - | probe 스크립트를 probeKey에 `TIME`·`HSET`·`PEXPIRE`·`HGET`·`DEL`을 실제 실행하는 것으로 교체하고, 테스트 ACL에 `+time` 추가 |
| G-10b | Consider | `redisRequired`가 REGULAR lane만 probe → ADVANCED 자격 증명이 깨져도 readiness UP | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): `RedisCorrectnessRoles.java:71` `anyScriptRoleSelected`(idempotency/rate-limit/lease), `RedisSdkAutoConfiguration.java:296`: 스크립트 role이 선택되면 `redisRequired`가 SCRIPT lane에서 `SCRIPT LOAD`+`EVALSHA`(`return 1`, key `<namespace>:probe:{health}:script`)도 확인(`RedisHealthContributor.java:92`). 실제 Redis `LiveRedisCompositionTest.aBrokenAdvancedAccountTakesRequiredRedisDown` FAIL(`expected: DOWN but was: UP`)→PASS, `aWorkingAdvancedAccountKeepsRequiredRedisUp` PASS. 단위 `RedisHealthContributorTest.aScriptLaneItsAccountCannotRunIsUnreachable` PASS | - | script capability가 선택되면 required contributor가 SCRIPT lane에서 등록 스크립트 EVALSHA로 probe |
| G-11a | Consider | application executor를 adapter leaf에서 조립하고 provider마다 lease·codec 적용이 다름 | 완료 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:32-55`(`IdempotencySettings` 하나로 한 번 조립), `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisIdempotencyConfig.java:31-35`(store만 제공). 「제거된 코드」 행 228. 테스트 `IdempotencyProviderCompositionTest.redisComposesOneExecutorOverTheRedisStoreAlone`. 커밋 `6d27356e` | - | - |
| G-11b | Consider | 소유자 결정: 멱등성 executor 조립을 별도 `composition:*` 모듈로 이동 — 아직 app-bootstrap에 있고 sample이 두 번째 executor를 조립 | 남음 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:28-55`, `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java:39`. `src/composition/`에는 fileserver·notification만 있음 | W3 | `composition:idempotency` leaf를 `modules.json`에 등록하고 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 옮긴 뒤 app-bootstrap·sample이 그 leaf를 쓰게 하고 `SampleIdempotencyConfig` 삭제 |
| G-11b | Consider | 소유자 결정: 멱등성 executor 조립을 별도 `composition:*` 모듈로 이동 — 아직 app-bootstrap에 있고 sample이 두 번째 executor를 조립 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): NEW-2b와 같다. `modules.json`에 `composition-idempotency`(edge application-core, adapter-outbound-support)를 등록했다. app-bootstrap과 sample이 `runtimeOnly project(':composition:idempotency')`를 쓴다. | - | `composition:idempotency` leaf를 `modules.json`에 등록하고 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 옮긴 뒤 app-bootstrap·sample이 그 leaf를 쓰게 하고 `SampleIdempotencyConfig` 삭제 |
| G-12a | Nit | `app-bootstrap/CLAUDE.md`가 없는 `autoconfigure/redis/RedisCapabilityConfig`·`RedisKeys`를 가리킴 | 완료 | `src/app-bootstrap/CLAUDE.md:92,102`가 `cache-redis`의 `capability/RedisCapabilityConfig`·`capability/RedisKeys`를 가리킴(두 파일 존재). 커밋 `6d27356e` | - | - |
| G-12b | Nit | `cache-redis/CLAUDE.md`의 Boot 버전 "4.0.0" 틀림 | 남음 | `src/adapter/outbound/cache-redis/CLAUDE.md:8`(실제 `src/gradle/libs.versions.toml:84` `4.0.8`). `:11` package root `…outbound.cache`는 실제 `…cache.redis`의 상위라 부정확 | W5 | `:8` 버전 줄 삭제(버전은 루트 CLAUDE.md가 소유)하고 `:11`을 `dev.caskeleton.adapter.outbound.cache.redis`로 수정 |
| G-12c | Nit | `src/README.md`가 orphaned key `APP_CACHE_REDIS_ENABLED`·`APP_CACHE_REDIS_CLIENT_MODE`를 동작하는 키처럼 설명 | 남음 | `src/README.md:312-317`(`CLIENT_MODE`가 managed/external을 고른다고 서술). `docs/registries/env-keys.yaml:2445-2480` `deprecated_orphaned: true`, Java 읽는 곳 0(sample yml `src/sample-portfolio/src/main/resources/application.yml:257-258`만 바인딩) | W5 | `src/README.md:312-313,316-317` 두 항목 삭제 |
@@ -682,8 +682,8 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| ID | 심각도 | 요약 | 상태 | 근거 | Wave | 수정 방향 |
|---|---|---|---|---|---|---|
| X1-지도-Outbox | 권고 | Outbox 저장 모델 3개·append 포트 4개·relay 3개 → 앱 1벌(v1 + fencing), messaging outbox 유지 | 남음 | V2 전부·Debezium 삭제(`docs/capability-status.md:130,175-179`), v1 + `V17__outbox_event_lease_fencing.sql`로 1벌(커밋 `6d27356e`). 남은 것: append 포트 2개(`LegacyOutboxAppendPort`, `OutboxAppendPort`), `CanonicalOutboxAppendAdapter` guard 없음, relay 조립이 app-bootstrap | W3 | X1-#1b(결정) 뒤 append 포트 1개만 남기고, X1-#1c guard 추가, X1-#1i로 relay 조립을 `composition:outbox-relay`로 이동 |
| X1-지도-요청 멱등성 | 권고 | 계약 2개·store 3개·executor 조립 3곳·inbound ledger 3개 → V2 정본, 조립 1곳 | 남음 | v1 삭제·V2 개명, websocket·graphql ledger 삭제(`docs/capability-status.md:226-232`). `new IdempotencyExecutor` 2곳: `IdempotencyProviderSelectionConfig.java:48`, sample `SampleIdempotencyConfig.java:39` | W3 | X1-#2b대로 `composition:idempotency` 신설 후 두 곳을 모듈 하나로 |
| X1-지도-Outbox | 권고 | Outbox 저장 모델 3개·append 포트 4개·relay 3개 → 앱 1벌(v1 + fencing), messaging outbox 유지 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **append 포트:** `OutboxAppendPort` 하나다(`src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java:15`). `LegacyOutboxAppendPort`는 삭제했다.<br>**구현:** `OutboxStoreAdapter implements OutboxAppendPort, OutboxStorePort`(`src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/OutboxStoreAdapter.java:48`). `CanonicalOutboxAppendAdapter`는 여기로 합쳤다.<br>**X1-#1c guard:** `append` 첫 줄의 `requireTransaction("append")`(`:65`)다.<br>**relay 조립:** `composition:outbox-relay`에 있다(`src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:53`).<br>**테스트:** `OutboxAppendContract`(application-core testFixtures)를 fake와 adapter가 공유한다. PostgreSQL lane `postgresqlOutboxAppendTransactionalIntegrationTest` 2, `postgresqlOutboxConcurrentRelayIntegrationTest` 4, `postgresqlOutboxRowLifecycleIntegrationTest` 10 PASS. | - | X1-#1b(결정) 뒤 append 포트 1개만 남기고, X1-#1c guard 추가, X1-#1i로 relay 조립을 `composition:outbox-relay`로 이동 |
| X1-지도-요청 멱등성 | 권고 | 계약 2개·store 3개·executor 조립 3곳·inbound ledger 3개 → V2 정본, 조립 1곳 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 조립이 한 곳이다(`composition:idempotency`). 두 root가 같은 모듈을 쓴다. | - | X1-#2b대로 `composition:idempotency` 신설 후 두 곳을 모듈 하나로 |
| X1-지도-자연키 생성-또는-반환 | 권고 | durable operation을 notification 방식(`ON CONFLICT`)으로, upsert executor 삭제 (= E-2) | 완료 | `DurableOperationJpaRepository.java:48` `ON CONFLICT … DO NOTHING`, `DurableOperationStoreAdapter.java:46-58` 삽입 후 재조회, upsert 실행기 7종 삭제(`docs/capability-status.md:158`), 커밋 `6d27356e` | - | - |
| X1-지도-Inbox / 소비자 dedup | 권고 | app-core inbox 삭제, 나머지(messaging inbox·notification ledger) 유지 | 완료 | `application/inbox/`·`PostgreSqlSameStoreInboxAdapter` 삭제(`docs/capability-status.md:155`), mongo change stream dedup 삭제(`:151`); application-core 패키지 목록에 `inbox` 없음, 커밋 `6d27356e` | - | - |
| X1-지도-lock / lease / fencing | 권고 | 미사용 포트·claim executor 삭제, fencing은 contract kit로 | 남음 | claim executor·`CacheRefreshCoordinationPort`·`LeaseWatchdog` 삭제(`docs/capability-status.md:152-153,157`). 남은 포트 2개 모두 비즈니스 소비자 0: `DistributedLockPort`(참조는 `StartupSafetyValidator.java:51` 존재 검사뿐), `DistributedLeasePort`(참조 0) | W3 | 결정(2026-09-25): lock·lease 유지, 쓰지 않는 claim executor만 삭제, fencing은 계약 테스트로 |
@@ -691,20 +691,20 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| X1-지도-Backoff 계산식 | 권고 | 10개, "full jitter" 뜻 3가지 → shared-contract `Backoff` | 남음 | 앱 쪽 3개 남음(`OutboxBackoffPolicy.java:63-68`, `ExponentialFullJitterBackoff.java:78`, `RetryBackoff.java:42`), JPA 2개 삭제 | W3 | X1-#9 |
| X1-지도-Rate limit | 권고 | web 전용 병렬 타입 세트 삭제 (= I-8 일부) | 완료 | `WebRateLimiter`·web `RateLimitDecision`·`RateLimitFailurePolicy`·`WebMvcThrottleFilter` 삭제(`docs/capability-status.md:99`); 남은 경로 `RateLimitWebConfig.java:22` → `EdgeRateLimitTransportBridge` → shared `EdgeRateLimitPort`, 커밋 `6d27356e` | - | - |
| X1-지도-Admission / in-flight | 권고 | 유지하되 gRPC check-then-increment는 `Semaphore`로 (= N-5) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): N-5a와 같은 수정. `Semaphore` 대신 한 락: in-flight와 queued 두 카운터를 한 결정에서 함께 봐야 해서 semaphore 두 개로는 원자적으로 안 된다. `GrpcAdmissionController.java:52`, `GrpcAdmissionControllerTest` | - | X1-#10a |
| X1-지도-Kafka producer | 권고 | legacy seam·platform 2개, 둘 다 TLS/SASL 없음 → outbox 정리에 포함 | 남음 | platform producer는 Wave 1(1-4)에서 보안 적용. legacy `KafkaSenderAutoConfiguration.java:60-80` `kafkaSeamProducer`에 `security.protocol`·SASL·SSL 설정 없음 | W1 | X1-#1f |
| X1-지도-Kafka producer | 권고 | legacy seam·platform 2개, 둘 다 TLS/SASL 없음 → outbox 정리에 포함 | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** legacy seam producer(`KafkaSenderAutoConfiguration`·`KafkaSender`·`LegacyKafkaMessagingRootAutoConfiguration`)를 `6268c494`에서 지웠다.<br>**남은 producer:** platform 하나다. `KafkaSecurityConfigurer`로 TLS/SASL을 적용한다: `src/messaging/messaging-spring-boot-starter-kafka/src/main/java/dev/caskeleton/messaging/autoconfigure/KafkaMessagingAutoConfiguration.java:188` `config.putAll(producerSecurity(...))`, `:216`.<br>**같은 결함 없음:** `MessagingSecuredBrokerQualificationTest`가 PASS다 — `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresSaslAsTheProviderUser`, `aPublishIsConfirmedByAPrivateCaBrokerThatRequiresAClientCertificate`, `:messaging:messaging-spring-boot-starter:integrationTest` 3/3. | - | X1-#1f |
| X1-지도-파일 control plane / canonical JSON | 권고 | 소비자 0인 `FilePublicationPort` plane 삭제, parser 3개 → 1개 | 완료 | publication R1/R2 31개·`FilePublicationPort`·`FileExportPort` 삭제(`docs/capability-status.md:76-77`), 남은 직접 파서 `objectstorage/control/CanonicalJsonReader.java` 1개, 커밋 `6d27356e` | - | - |
| X1-지도-readiness / evidence / API-surface / moduleboundary | 권고 | 카드 스키마·검증기·API-surface gate·moduleboundary 여러 벌 → 하나로 | 남음 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): 완료: JPA readiness·evidence → persistence-jpa 테스트(manifest 폐기), API surface 구현 하나. 남은 "messaging 카드 검증은 messaging leaf로": `MessagingCapabilityRegistryContractTest`는 `config/messaging/*.yaml`을 snakeyaml로 읽는데 `adapter:outbound:messaging`은 모든 configuration(테스트 포함)에서 YAML·Jackson 2를 exclude+reject한다("Jackson 3 only and YAML-free"). 옮기려면 카드 파일을 JSON으로 바꾸거나 test 설정만 예외로 둘지 정해야 함. 승인자: 저장소 소유자 결정 필요<br>결정 29·31(2026-09-28): 보류 해제 → 남음, 빌드 잔여 묶음 P27 | W3 | 결정(2026-09-25): O3 — JPA readiness·evidence는 persistence-jpa 테스트로(manifest 폐기), messaging 카드 검증은 messaging leaf로 |
| X1-지도-테스트 fake / contract kit | 권고 | 같은 포트 fake가 모듈마다 따로 → 포트 소유 leaf testFixtures에 contract kit | 남음 | `TransactionPort` fake 21 → 10, kit 4개(DurableOperation·OutboxLeaseFencing·GrpcOperationLedger·sample WorkLogRepository) | W4 | X1-#3a~#3d |
| X1-#1a | Required | Outbox V2 삭제 + v1 claim에 owner+token fencing 이식 | 완료 | `persistence-jpa/.../db/migration/postgresql/V17__outbox_event_lease_fencing.sql`, `OutboxStoreAdapter.java:102-123`(markPublished·markFailed·markDead가 `lease.owner()`·`lease.token()` 조건부 UPDATE), V2 코드·`jpa/outbox-storage`·`jpa/outbox-polling` 삭제(`docs/capability-status.md:175-179`), 커밋 `6d27356e` | - | - |
| X1-#1b | Required | append 포트를 `OutboxAppendPort` 하나로, legacy는 cutover 후 삭제 | 남음 | `OutboxAppendPort` main 소비자 0(구현 `CanonicalOutboxAppendAdapter`뿐). `LegacyOutboxAppendPort` 소비자 4곳: `SubmitDurableOperationUseCase.java:56`, sample `PosterEventPublisher.java:25`·`PosterImagePublicationEventPublisher.java:12`·`CreateWorkLogUseCase.java:42`. canonical 경로는 `IntegrationEventEncoderPort` 구현이 필요한데 템플릿은 주지 않음(`src/messaging/CLAUDE.md:83-89`, main 구현 0) | W3 | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) |
| X1-#1b | Required | append 포트를 `OutboxAppendPort` 하나로, legacy는 cutover 후 삭제 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **소비자 4곳 이전:** `SubmitDurableOperationUseCase`(`src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java:72`, 계약 `DurableOperationSubmittedContract`)와 sample 3곳이 `OutboxAppendPort`를 쓴다.<br>**encoder:** 템플릿 encoder `JsonIntegrationEventEncoder`(`src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/messaging/JsonIntegrationEventEncoder.java:47`)와 `IntegrationEventEncoderAutoConfiguration`.<br>**테스트:** `JsonIntegrationEventEncoderTest`, `IntegrationEventEncoderAutoConfigurationTest`, `DurableOperationSubmissionOutboxIntegrationTest`(실제 encoder) PASS. | - | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) |
| X1-#1c | Required | `CanonicalOutboxAppendAdapter`에 caller 트랜잭션 guard 없음 (= E-3) | 남음 | `CanonicalOutboxAppendAdapter.java:36-75` `append`가 트랜잭션 확인 없이 `repository.save` | W3 | X1-#4 helper를 `append` 첫 줄에서 호출(1곳) + 트랜잭션 없이 부르면 거부되는 테스트 |
| X1-#1d | Required | canonical 이벤트가 v1 claim을 타며 aggregate 순서·tenant 범위를 잃음 (= E-5) | 완료 | Wave 1–2 P9 (fcddab7e·Wave 2 커밋): E-5a·E-5b와 같은 변경 — canonical row claim 순서를 tenant·type·id + sequence·index로(PostgreSQL·H2 SQL), migration V18 index | - | X1-#1b에서 canonical 경로를 남기면: canonical row(`contract_id IS NOT NULL`) gate를 `(tenant_scope, aggregate_type, aggregate_id)` + `(aggregate_sequence, event_index)` 순서로, `H2OutboxClaimRepository`도 동일 |
| X1-#1f | Required | legacy Kafka producer에 TLS/SASL 없음 (Critical #8 = M-2와 같은 문제) | 남음 | `adapter/outbound/messaging-kafka/.../KafkaSenderAutoConfiguration.java:60-80` producer config에 bootstrap·serializer·acks·timeout만 | W1 | `KafkaAdapterSettings`에 security 블록(protocol·SASL·truststore) 추가 후 `kafkaSeamProducer` config에 반영, 또는 X1-#1b 결정으로 seam 자체 삭제 |
| X1-#1f | Required | legacy Kafka producer에 TLS/SASL 없음 (Critical #8 = M-2와 같은 문제) | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 위와 같다. 보안 블록을 추가할 대상인 `KafkaAdapterSettings`·`kafkaSeamProducer`가 `6268c494`에서 삭제됐다. canonical 경로의 producer는 `KafkaMessagingAutoConfiguration.java:188`에서 보안 profile을 적용하고, `MessagingSecuredBrokerQualificationTest` 2/2가 PASS다. | - | `KafkaAdapterSettings`에 security 블록(protocol·SASL·truststore) 추가 후 `kafkaSeamProducer` config에 반영, 또는 X1-#1b 결정으로 seam 자체 삭제 |
| X1-#1g | Required | `src/messaging/CLAUDE.md`에 "앱은 `messaging_outbox`를 쓰지 않는다" 명시 | 남음 | `grep -n messaging_outbox src/messaging/CLAUDE.md` → 0건 | W5 | `src/messaging/CLAUDE.md` MSG-015 절(:60-89)에 한 줄 추가 |
| X1-#1h | Required | fencing 시나리오를 contract kit로 fake·실제 adapter 양쪽에서 실행 | 완료 | testFixtures `OutboxLeaseFencingContract`를 `InMemoryOutboxStoreLeaseFencingContractTest.java:9`와 `PostgreSqlLegacyOutboxConcurrentRelayIntegrationTest.java:45`가 상속, 커밋 `6d27356e` | - | - |
| X1-#1i | 권고 | outbox relay 조립이 app-bootstrap에 남음(소유자 결정: `composition:*`로 이동) | 남음 | `app-bootstrap/.../autoconfigure/outbox/OutboxConfig.java:44-118`이 `PublishPendingOutboxEventsUseCase`·`OutboxRelayScheduler` 생성, `AutoConfiguration.imports:2`. persistence-jpa로는 `AdapterBoundaryArchitectureTest.java:207` `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 때문에 못 옮김 | W3 | 새 leaf `composition:outbox-relay`(edge: application-core, adapter-outbound-support) 등록, `OutboxConfig`·`OutboxSettings`·`OutboxRelayScheduler`·`OutboxMetrics`·`OutboxLeaderElectionToken`·`OutboxCanonicalTransportRequirementValidator` 6개 + 테스트 5개 이동, app-bootstrap은 `runtimeOnly` 한 줄 |
| X1-#1i | 권고 | outbox relay 조립이 app-bootstrap에 남음(소유자 결정: `composition:*`로 이동) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **이동:** `OutboxConfig`→`OutboxRelayAutoConfiguration`, 그리고 `OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken`을 `src/composition/outbox-relay`로 옮겼다(`a053ae89`).<br>**삭제:** `OutboxCanonicalTransportRequirementValidator`는 옮기지 않고 삭제했다. 켜고 끌 canonical 플래그가 더는 없다.<br>**연결:** app-bootstrap은 `runtimeOnly project(':composition:outbox-relay')` 한 줄로 받는다.<br>**테스트:** `OutboxRelayAutoConfigurationTest`(`aMisspeltOutboxKeyFailsStartupInsteadOfLeavingTheDefaultInForce` 포함), `OutboxRelaySchedulerLoggingTest` PASS. | - | 새 leaf `composition:outbox-relay`(edge: application-core, adapter-outbound-support) 등록, `OutboxConfig`·`OutboxSettings`·`OutboxRelayScheduler`·`OutboxMetrics`·`OutboxLeaderElectionToken`·`OutboxCanonicalTransportRequirementValidator` 6개 + 테스트 5개 이동, app-bootstrap은 `runtimeOnly` 한 줄 |
| X1-#2a | Required | 멱등성 V2를 정본으로, v1 삭제, 이름에서 `V2` 제거, sample을 V2로 | 완료 | `application/idempotency/IdempotencyExecutor.java`·`IdempotencyStorePort.java`(V2 개명), v1 모델·JPA v1 store·bootstrap v1 조립 삭제(`docs/capability-status.md:226-229`), sample `PublishPosterImageUseCase`가 `IdempotencyExecutor` 사용. v1 완료 기록 결함(= A-8)도 함께 소멸. 커밋 `6d27356e` | - | - |
| X1-#2b | Required | executor 조립 1곳, provider는 store bean만 (= G-11 일부) | 남음 | Redis·PG provider는 store만 기여(`RedisIdempotencyConfig`·`PostgreSqlIdempotencyStoreConfig`에 executor 생성 0). executor 생성 2곳: `IdempotencyProviderSelectionConfig.java:48`, sample `SampleIdempotencyConfig.java:39`(같은 키·기본값을 `Binder`로 복사) | W3 | 새 leaf `composition:idempotency`(edge: application-core, adapter-outbound-support)로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` + 테스트 2개 이동, app-bootstrap·sample 둘 다 `runtimeOnly`; `SampleIdempotencyConfig`는 executor bean 삭제(Clock·`@EnableScheduling`만 유지) |
| X1-#2b | Required | executor 조립 1곳, provider는 store bean만 (= G-11 일부) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): executor 생성은 한 곳이다: `IdempotencyAutoConfiguration.java:58`. main에 `new IdempotencyExecutor`는 여기뿐이다. web testFixtures의 fault fixture는 테스트용이다. provider는 store bean만 기여한다. | - | 새 leaf `composition:idempotency`(edge: application-core, adapter-outbound-support)로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings` + 테스트 2개 이동, app-bootstrap·sample 둘 다 `runtimeOnly`; `SampleIdempotencyConfig`는 executor bean 삭제(Clock·`@EnableScheduling`만 유지) |
| X1-#2c | Required | websocket `CommittedResultLedger`(inbound가 가진 저장 SPI) 삭제 | 완료 | websocket command ledger 일체 삭제(`docs/capability-status.md:230`), websocket main 참조 0, 커밋 `6d27356e` | - | - |
| X1-#2e | Required | `DurableOperationStoreAdapter`를 `ON CONFLICT` 방식으로, upsert executor 삭제 (= E-2) | 완료 | X1-지도-자연키 행과 같은 근거(`DurableOperationJpaRepository.java:48`, `docs/capability-status.md:158`), 커밋 `6d27356e` | - | - |
| X1-#3a | Required | `TransactionPort` fake를 application-core testFixtures 1개로 | 남음 | testFixtures `DirectTransactionPort` 생김(사용 14파일), sample 6개는 0으로. 남은 자체 fake 10개: application-core test 4(`SubmitDurableOperationUseCaseTest`, `OutcomeAwareRelayTest`, `PublishPendingOutboxEventsUseCaseTest`, `TransactionPortTest`), application-notification 4(`PlatformFakes`, `AdminOperationExecutorTest`, `CallbackIngestionAtomicityTest`, `ProviderEventLateMatchTest`), application-fileserver `DirectTransactions`, composition `FileserverAssemblyFixture` (측정: 테스트 source set에서 `git grep -E "implements (\w+\.)*TransactionPort\b\|new (\w+\.)*TransactionPort\(\)"`) | W4 | 그냥 실행만 하는 fake는 `DirectTransactionPort`로 교체(application-notification·application-fileserver·composition에 application-core testFixtures 의존 추가), 호출 기록이 필요한 outbox relay fake만 유지 |
@@ -774,7 +774,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
|---|---|---|---|---|---|---|
| S1-#1 | Required | 멱등성 엔진 2세대 공존, V2는 호출자 0 (= X1-#2, A-8) | 완료 | `6d27356e`: v1 삭제(「제거된 코드」 멱등성 v1 모델·JPA v1 store·bootstrap 조립 행), V2가 이름 없이 `application-core/.../idempotency/IdempotencyExecutor.java`로 정본. 조립은 `app-bootstrap/.../idempotency/IdempotencyProviderSelectionConfig.java:36-55` 한 곳(store 개수 검사 포함), provider는 store만(`cache-redis/.../capability/RedisIdempotencyConfig.java:51`) | - | - |
| S1-#2a | Required | outbox V2 append·폴링 포트, `OutboxV2RetryPolicy` (= X1-#1, A-3) | 해당 없음(코드 삭제) | 「제거된 코드」 "application-core outbox V2 포트·유스케이스 17종" 행. `application-core/.../outbox/`에 V2 파일 0, 폴링 `OutboxStorePort` 1개·retry `OutboxBackoffPolicy` 1개만 남음 | - | - |
| S1-#2b / S2-#4b | Required | append 포트 2개(legacy·canonical)가 같은 `outbox_event`에 공존, `ClaimedOutboxEvent` sealed 합집합 유지 (= X1-#1) | 남음 | `application-core/.../outbox/LegacyOutboxAppendPort.java:11`(sample 4곳 + `SubmitDurableOperationUseCase` 사용), `OutboxAppendPort.java:13`(main 호출자 0, 구현 `CanonicalOutboxAppendAdapter`뿐), `ClaimedOutboxEvent.java:11` `permits OutboxEvent, CanonicalClaimedOutboxEvent`<br>S2-#4b: `persistence-jpa/.../outbox/entity/OutboxEventEntity.java` public 62개, `outbox/OutboxStoreAdapter.java`(legacy) + `CanonicalOutboxAppendAdapter.java:28` | W3 | 결정(2026-09-25): canonical 통일 — 템플릿 JSON encoder 제공, `LegacyOutboxAppendPort` 소비자 4곳 이전 후 legacy 포트·legacy Kafka 발행 경로 삭제<br>S2-#4b: 결정(2026-09-25): canonical 통일 → legacy adapter·컬럼 접근자 삭제(적용된 migration 유지) |
| S1-#2b / S2-#4b | Required | append 포트 2개(legacy·canonical)가 같은 `outbox_event`에 공존, `ClaimedOutboxEvent` sealed 합집합 유지 (= X1-#1) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **application-core:** `ClaimedOutboxEvent`는 이제 sealed 합집합이 아니다. `record(ValidatedIntegrationEvent event, OutboxEventStatus status, int attemptCount)`(`ClaimedOutboxEvent.java:19`)다.<br>**persistence-jpa:** legacy adapter와 entity의 `payload`·`idempotencyKey` 접근자를 삭제했다. canonical metadata가 불완전한 row는 claim할 때 DEAD가 된다. claim SQL(PG·H2)에서 legacy CASE를 없앴다.<br>**V19:** 미발행 pre-canonical row가 있으면 migration이 실패한다. CHECK `ck_outbox_event_canonical_unless_published`를 추가했다.<br>**테스트:** `PostgreSqlOutboxClaimAndMaintenanceIntegrationTest.aRowWithoutTheCanonicalEnvelopeIsRefusedUnlessItIsPublished`·`aPublishedPreCanonicalRowIsKeptForTheReaper`·`theCanonicalOnlyMigrationRefusesADatabaseThatStillHoldsAnUndeliveredPreCanonicalRow` PASS(jpaPlatformContractTest 221, 이 클래스 9/9). `H2ClaimSqlTest`, `OutboxStoreAdapterTest` PASS. | - | 결정(2026-09-25): canonical 통일 — 템플릿 JSON encoder 제공, `LegacyOutboxAppendPort` 소비자 4곳 이전 후 legacy 포트·legacy Kafka 발행 경로 삭제<br>S2-#4b: 결정(2026-09-25): canonical 통일 → legacy adapter·컬럼 접근자 삭제(적용된 migration 유지) |
| S1-#3a | Required | 호출자 없는 cache executor 20종·`LeaseWatchdog`·`TransactionCompletionResolver`·inbox·filepublication·`EphemeralFanoutPort` | 해당 없음(코드 삭제) | 「제거된 코드」 application-core cache 20종, `LeaseWatchdog`, `TransactionCompletionResolver`, same-store inbox, `FilePublicationPort`, `EphemeralFanoutPort` 행 | - | - |
| S1-#3b | Required | `lease/*` 399줄: Redis 구현만 있고 use case 호출자 0 (= X1-#6) | 남음 | `application-core/.../lease/`(13파일 399줄) 참조는 `cache-redis/.../lease/RedisDistributedLeaseAdapter.java`·`RedisLeaseConfig.java`뿐. JDBC `DistributedLockPort`도 비즈니스 소비자 0. cache-redis README가 lease를 제공 capability로 명시 | W4 | 결정(2026-09-25): lock·lease 둘 다 capability로 유지 — 포트별 추상 계약 테스트를 fake와 어댑터가 함께 통과 |
| S1-#4 | Required | `NotificationDispatchService` 생성자 15개, record 필드별 재조립·실패 분류가 한 클래스에 (B-5 구조 원인) | 남음 | `application-notification/.../dispatch/NotificationDispatchService.java:72`(인자 15개), `:208`·`:485` record 재조립, `:255-288` catch 분기, `:475`·`:513` 종료 상태 두 번 계산. `DispatchOutcomeRecorder.java:67,110` 재조립 2곳 | W3 | `DeliveryAttemptRecord.completed(result, at)`·`RecipientDeliveryRecord.advancedRoute(now)` 전이 메서드 추가, catch 분기는 `ProviderOutcomeClassifier` 정적 메서드로 분리 |
@@ -803,7 +803,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S1-#20 | Nit | notification `dispatch/` 패키지에 여러 기능 | 남음 | `application-notification/.../platform/dispatch/` 46파일 3,855줄(제출·템플릿 게시·`ContactPoint*`·reconciliation 포함) | W5 | `submission/`, `dispatch/`, `reconciliation/`로 이동, `ContactPoint*`는 `contact/`로 |
| S1-lead-1 | 권고 | messaging 자체 outbox/inbox와 app-core outbox/inbox가 같은 패턴 3~4벌 | 완료 | app-core inbox 삭제(「제거된 코드」 same-store inbox 행), outbox V2 삭제. 남은 2벌(app outbox + vendored `messaging_outbox`)은 D2 결정(`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md:104` "messaging platform outbox는 vendored라 유지") | - | - |
| S1-lead-2 | 권고 | UUID 생성기 제각각 | 남음 | notification 자체 `adapter/outbound/notification/.../dispatch/UuidV7Generator.java`, fileserver `RandomUploadIdentifierFactory`(v4), sample `Uuid*IdFactory`(uuid-creator v7) | W3 | notification `UuidV7Generator`를 sample이 쓰는 uuid-creator로 대체(v7 생성 1벌), fileserver v4는 유지 |
| S1-lead-3 | 권고 | 멱등성 executor 조립 위치 (= G-11) | 남음 | adapter 조립은 사라졌으나(`RedisIdempotencyConfig.java:51` store만) 조립이 `app-bootstrap/.../idempotency/IdempotencyProviderSelectionConfig.java:48`에 있음. 소유자 결정은 별도 `composition:*` 모듈 | W3 | `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 새 `composition:idempotency`(가칭) 모듈로 이동, registry 등록 |
| S1-lead-3 | 권고 | 멱등성 executor 조립 위치 (= G-11) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): NEW-2b와 같다. | - | `IdempotencyProviderSelectionConfig`·`IdempotencySettings`를 새 `composition:idempotency`(가칭) 모듈로 이동, registry 등록 |
| S1-lead-4 | 권고 | `Local*Gateway`가 `LocalBlockingContentStore`로 넘기기만 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `b4fe7c8b`. `LocalBlockingContentStore`가 `DownloadContentPort`·`ZeroCopyDownloadPort`를 직접 구현(`platform/local/LocalBlockingContentStore.java:47`), `LocalDownloadContentGateway`·`LocalZeroCopyDownloadGateway`와 bean 2개 삭제. `LocalCleanupContentGateway`는 `purgeQuarantined`를 orphan scan에 넘기는 두 협력자 조합이라 위임 전용이 아니어서 유지. `LocalStorageGatewayContractTest` PASS | - | 위임만 하는 3개는 `LocalBlockingContentStore`가 해당 gateway 인터페이스를 직접 구현, 로직 있는 Copy/Upload는 유지 |
| S1-lead-5 | 권고 | persistence-jpa `SpringPolicyTransactionPort` 정리 | 해당 없음(코드 삭제) | 「제거된 코드」 `SpringPolicyTransactionPort`… 행 | - | - |
| S1-lead-6 | 권고 | fileserver 전이 규칙이 Java와 SQL 두 곳 | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): SQL의 허용 상태 문자열을 없애고 `JpaFileMetadataStore`가 전이표(`FileStateMachine.canTransition(s, DELETING)`)에서 목록을 만들어 파라미터로 넘긴다: `src/adapter/outbound/persistence-fileserver/.../repository/FileTransitionRepository.java:73`, `JpaFileMetadataStore.java:56`. 동작이 바뀐 게 아니라 중복 제거라 FAIL 재현 대상이 없음. PG `aRecordInAStateWithNoDeletingEdgeIsNotMarkedDeleting`(VERIFYING 거부)·기존 `logicalDeleteMovesTheRecordOutOfPublicReadability` PASS | - | SQL의 허용 상태 목록을 `FileState` 전이표에서 파라미터로 넘기거나, 두 목록이 같은지 단언하는 테스트 추가 |
@@ -821,7 +821,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S2-#8a | Consider | 조립 방식 3가지, 게이트 반복 | 남음 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java`(스캔 stereotype 16개), `notification/configuration/NotificationJpaPersistenceFacade.java`, `persistence-fileserver/.../FileserverJpaPersistenceConfig.java` + fileserver main `@ConditionalOnProperty` 10개, Mongo 6개 | W3 | feature config별 명시적 `@Bean` 한 방식으로, 클래스별 stereotype·조건 제거 |
| S2-#8b | Consider | "두 조립 루트가 `dev.caskeleton.adapter`를 스캔한다" 서술이 사실과 다름 | 남음 | `persistence-jpa/.../postgresql/idempotency/PostgreSqlOwnerSafeIdempotencyStore.java:53`, `src/test/.../CandidateAdapterCompositionTest.java:10-18`(현재 `CaSkeletonApplication`은 scan 제외식 없음, sample은 `SamplePortfolioApplication.java:31-40`처럼 좁게 스캔) | W5 | 잘못된 단락 삭제, 전제가 사라진 `CandidateAdapterCompositionTest` 삭제 또는 현재 조립 기준으로 재작성 |
| S2-#9a | Consider | 무관한 `inbox` 패키지 2개 | 해당 없음(코드 삭제) | `postgresql/inbox` 삭제(「제거된 코드」 same-store inbox 행) | - | - |
| S2-#9b | Consider | feature가 vendor별로 흩어짐 | 남음 | outbox: `outbox/`, `outbox/entity/`, `postgresql/PostgreSqlOutboxClaimRepository.java`, `h2/H2OutboxClaimRepository.java`; 멱등성: `idempotency/`, `postgresql/idempotency/`, migration `jpa/idempotency` + `postgresql/V1,V10` | W3 | feature 기준 패키지(`outbox/{jpa,postgresql,h2}`, `idempotency/{jpa,postgresql}`)로 이동만 |
| S2-#9b | Consider | feature가 vendor별로 흩어짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 이동만 했다(`910ab7ab`). 새 패키지는 `persistence/outbox/{jpa(+entity),postgresql,h2}`, `persistence/idempotency/{jpa(+entity),postgresql}`다. JPA API surface는 `updateJpaApiSurface -PapproveJpaApiSurfaceChange`로 다시 승인했다. `JpaModuleBoundaryTest`에 autoconfigure→idempotency edge를 기록했다. `verifyJpaApiSurface`·`verifyJpaReadinessRegistry` PASS. | - | feature 기준 패키지(`outbox/{jpa,postgresql,h2}`, `idempotency/{jpa,postgresql}`)로 이동만 |
| S2-#10 | Consider | promotion/benchmark gate가 production classpath에 | 해당 없음(코드 삭제) | 「제거된 코드」 `experimental/next/*`, `MongoAdvancedPromotionGate`·`Evidence`, search·vector(benchmark·readiness gate 포함) 행. grep 0 | - | - |
| S2-#12 | Consider | Javadoc이 이력을 서술 | 남음 | 재측정: "used to/until now/never was/no longer" 포함 파일 jpa 25·mongo 36·fileserver 6 | W5 | 불변 조건 1~2줄만 남기고 이력은 git/ADR로 |
| S2-#13a | Nit | `JpaTransactionAutoConfiguration` 팩토리 2회 생성, `new JpaTransactionSettings(null ×9)` | 해당 없음(코드 삭제) | 「제거된 코드」 두 번째 엔진(`JpaTransactionAutoConfiguration`)·`JpaTransactionSettings` 행 | - | - |
@@ -830,7 +830,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S2-#14b | Nit | jpa API surface 파일에 옮겨간 타입 | 남음 | `docs/architecture/jpa-adopter-api-surface.txt:11` `...persistence.fileserver.FileserverSchemaActivation`(지금은 persistence-fileserver leaf) | W5 | 해당 줄 삭제(필요하면 fileserver 쪽 surface로) |
| S2-#14c | Nit | Mongo CLAUDE.md `MongoAdvancedProperties` 오기 | 완료 | `6d27356e`: 해당 이름 없음, `adapter/outbound/persistence-mongo/CLAUDE.md:146`이 "flags have no configuration property"로 갱신(`MongoAdvancedSettings`도 삭제) | - | - |
| S2-#14d | Nit | `JpaAdapterComponentsConfig`가 classpath 밖 leaf로 `{@link}` | 완료 | `persistence-jpa/.../config/JpaAdapterComponentsConfig.java:36`이 `{@code FileserverJpaPersistenceConfig}`로 변경(`208077fd`에서는 `{@link`) | - | - |
| S2-lead-1 | 권고 | app-core 포트 버전이 #4의 원인 | 남음 | V2 포트는 삭제됐으나 `OutboxAppendPort`/`LegacyOutboxAppendPort` 2개 남음(S1-#2b 근거와 같음). 멱등성은 `IdempotencyStorePort` 하나 | W3 | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) |
| S2-lead-1 | 권고 | app-core 포트 버전이 #4의 원인 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): 포트 버전이 하나로 줄었다: `OutboxAppendPort`(append)와 `OutboxStorePort`(claim/완료). 근거는 S1-#2b와 같다. | - | 결정(2026-09-25): canonical 통일(S1-#2b와 같은 작업) |
| S2-lead-2 | 권고 | 멱등성 claim 판정표가 Redis·PG에 따로 (= X1-#3) | 남음 | Redis 판정은 Lua 안(`cache-redis/.../idempotency/IdempotencyScripts.java`) + 응답 매핑 `RedisIdempotencyStoreAdapter.java:135-157`, PG는 `postgresql/idempotency/IdempotencyClaimGateway.java`. 공통 계약 테스트 없음(`application-core/src/testFixtures/.../idempotency/testkit/`에 `InMemoryIdempotencyStore`만) | W4 | application-core testFixtures에 `IdempotencyStoreContract` 추가, InMemory·Redis·PG adapter가 모두 상속 |
| S2-lead-3 | 권고 | 서명 cursor codec 여러 벌 (= X2 P1-4) | 남음 | web `CursorCodec`·`HmacWebCursorCodec` 삭제(「제거된 코드」 서명 커서 코덱·2세대 페이지네이션 행). 남은 3벌: `persistence-jpa/.../api/query/SignedJsonCursorCodec.java`, `persistence-mongo/.../query/pagination/MongoKeysetCursorCodec.java`, `graphql/.../pagination/HmacGraphQlCursorCodec.java` | W3 | X2 P1-4대로 서명은 inbound 한 계층, persistence는 typed keyset만(jpa·mongo codec 삭제 또는 서명 제거) |
| S2-lead-4 | 권고 | persistence 실패 예외 계층 3벌 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): `JpaPersistenceExceptionCodeTest.aJpaFailureCarriesTheOperationalCodeOfItsCategory` 16건 FAIL(`Expecting actual throwable to be an instance of: PersistenceFailureException`)→PASS. `persistence-jpa/.../api/error/JpaPersistenceException.java:22`(상속), `:59`(`FailureCategory`→`DB_*`; 직렬화 후에도 `errorCode()`가 category에서 계산). 대응 코드가 없던 2개는 `DB_OPTIMISTIC_CONFLICT`(CONFLICT/409/false)·`DB_COMPLETION_UNKNOWN`(DATA_INTEGRITY/500/false) 신설, SCHEMA_MISMATCH·DATA_CORRUPTION·ENTITY_NOT_FOUND·UNKNOWN은 이전 catch-all과 같은 `INTERNAL_ERROR`. `LockFailureClassificationContractTest`의 REGISTRY-GAP-1("optimistic 코드 없음") 고정 테스트를 `anOptimisticLockConflictIsANonRetryableConflict`로 승격. testFixtures에 `:shared-contract` 추가(mongo는 edge 없어 유지) | - | `JpaPersistenceException`이 `PersistenceFailureException`을 상속해 inbound가 한 계층만 매핑(mongo는 edge 없어 유지) |
@@ -907,7 +907,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S4-lead-2 | 권고 | 로컬 보안 파일시스템 primitive가 fileserver·objectstorage에 따로 있음 | 남음 | fileserver `platform/local/SafeFileChannelFactory.java:250`(`SecureDirectoryStream`)·`SecureDirectoryWalk.java`. objectstorage `filesystem/LocalObjectPathGuard.java:62-117`은 경로 검사 후 사용 방식(`rejectExistingLinks` → 생성). 방식과 검사가 다름. objectstorage는 `adapter-outbound-support` edge가 없음<br>Wave 3 W3-P24: 미완 — 이유: fileserver primitive 중 `SecureDirectoryWalk`는 JDK만 쓰지만 `SafeFileChannelFactory`는 `IOException`을 Fileserver 에러 코드로 바꾸는 번역을 품고 있어, support로 올리려면 에러 어휘를 떼어 내야 한다. 그리고 objectstorage `LocalObjectPathGuard`는 Path를 돌려주고 호출자(`LocalDevObjectDataStore`·`LocalDevObjectControlStore`·`LocalObjectStreamTransfer`, 약 520줄)가 `Files.*`로 여는 구조라, primitive를 쓰려면 이 I/O를 fd 기준(`SecureDirectoryStream`) 연산으로 다시 써야 한다. registry edge 추가만으로는 끝나지 않는 보안 민감 재작성이라 별도 묶음(권고 행)으로 남김 | W3 | fileserver 쪽 primitive를 `adapter:outbound:support`로 올리고, objectstorage에 support edge를 추가해서 `LocalObjectPathGuard`가 그것을 쓴다(registry 수정 포함) |
| S4-lead-3 | 권고 | notification 자체 JDK HTTP gateway·SigV4 서명기 vs httpclient leaf·AWS SDK | 남음 | `provider/http/*` 464줄(`JdkNotificationHttpGateway` 외), `ses/AwsSignatureV4Signer.java` 147줄. notification `build.gradle`에는 AWS SDK·httpclient 의존 없음. objectstorage만 AWS SDK를 씀 | W3 | 결정(2026-09-25): AWS SDK(sesv2)로 교체, 자체 JDK gateway·SigV4 서명기 삭제 |
| S4-lead-4a | 권고 | adapter `LocalJsonSchemaRegistry` vs vendored `messaging-schema-json` | 해당 없음(코드 삭제) | `LocalJsonSchemaRegistry` grep 0건. 「제거된 코드」 표 123행 | - | - |
| S4-lead-4b | 권고 | `adapter:outbound:messaging-kafka`(R0 seam) vs vendored `messaging/messaging-kafka` | 남음 | `src/adapter/outbound/messaging-kafka` main 371줄(`LegacyKafkaMessagingRootAutoConfiguration`, `KafkaSender`, `KafkaMessageBroker`). legacy outbox가 `OutboxMessagePublishAdapter` → `MessageBroker`로 이 경로를 씀. `src/messaging/CLAUDE.md:75-78`에 MSG-015 cutover가 끝나지 않았다고 적혀 있음 | W3 | legacy `OutboxEvent`에 canonical metadata를 채우는 migration 후 relay를 bridge로 바꾸고 `adapter:outbound:messaging-kafka`와 `core/MessageBroker` 계열 삭제 |
| S4-lead-4b | 권고 | `adapter:outbound:messaging-kafka`(R0 seam) vs vendored `messaging/messaging-kafka` | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** `core/MessageBroker` 계열(MessageBroker, MessagePublisher, OutboundMessage, OutboundMessagePublisher, DisabledMessagePublisher)과 `OutboxEnvelopeJson`, `adapter:outbound:messaging-kafka`의 Java 코드 전부.<br>**relay 경로:** relay는 claim한 row의 `ValidatedIntegrationEvent`를 bridge로만 보낸다(`OutboxMessagePublishAdapter(IntegrationEventPublishPort)`, `src/adapter/outbound/messaging/src/main/java/dev/caskeleton/adapter/outbound/messaging/outbox/OutboxMessagePublishAdapter.java:23`).<br>**leaf를 남긴 이유:** 계획은 leaf 삭제였다. 대신 bridge+starter-kafka를 싣는 코드 없는 capability 묶음으로 남겼다. 한 줄 선택이 유지되고, bridge leaf는 broker 중립으로 남는다.<br>**테스트:** `KafkaCapabilityActivationTest` PASS. | - | legacy `OutboxEvent`에 canonical metadata를 채우는 migration 후 relay를 bridge로 바꾸고 `adapter:outbound:messaging-kafka`와 `core/MessageBroker` 계열 삭제 |
| S4-lead-5 | 권고 | `ProviderCapabilities` 위치 인자 11개 → named factory | 남음 | S4-#4b와 같음 | W3 | S4-#4b 참조 |
| S5-#1a | Required | WebProblem 어휘(`ProblemCode`·`ProblemCatalog`·yaml·핸들러·writer) (= X2-P2-1) | 완료 | `ProblemCatalog`·`WebProblem`·`problem-catalog.yaml`·`ThrottleProblemWriter`·`WebMvcBudgetExceptionHandler` grep 0건. 「제거된 코드」 표 99·104·105행, `6d27356e` | - | - |
| S5-#1b | Required | 검증 규칙표 두 벌(`ClientSafeValidationDetails` vs `WebValidationIssueMapper`) | 완료 | `W/validation/` 삭제(표 103행). 남은 것은 `web/error/ClientSafeValidationDetails.java` 하나 | - | - |
@@ -976,7 +976,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S6-#5 | Required | fileserver가 build에서 빠졌는데 스위치·설정이 root에 남음 | 완료 | `dependencyPolicy` 없음, 한 줄 선택(`src/app-bootstrap/build.gradle:152`), 설정은 모듈 소유(`CS:37`, `CS:234`), `MasterSwitch.FILESERVER*` 삭제(`CS:78`), composition 자체 imports(`src/composition/fileserver-platform/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports`), `6d27356e` | - | - |
| S6-#6a | Required | 멱등성 설정 binder 3개·yml 2개, PG provider 하드코딩 (= X1-#2) | 완료 | settings record 하나 `IdempotencySettings`(`BS/autoconfigure/idempotency/IdempotencySettings.java:24-34`, prefix `ca-skeleton.capabilities.idempotency`), `config/idempotency.yml`·`IdempotencyProviderSettings`·`PostgreSqlIdempotencyProviderConfig` 삭제(`CS:228`), `APP_IDEMPOTENCY_TTL` 한 키(`src/app-bootstrap/src/main/resources/config/capabilities.yml:14`) | - | - |
| S6-#6b | Required | `APP_RATE_LIMIT_DEFAULT_POLICY_ID`가 두 키에 바인딩 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): 두 키 모두 읽히고 있었다(web `EdgeRateLimitTransportSettings`가 `app.rate-limit.*`, cache-redis `RedisRateLimitConfig`가 `ca-skeleton.capabilities.rate-limit.default-policy-id`). 소유자 결정 16(`app.*` 통일)에 맞춰 `app.rate-limit.default-policy-id` 하나만 남김: `cache-redis.yml:65` 줄과 `RedisCapabilitySettings.RateLimit.defaultPolicyId` 삭제, `RedisRateLimitConfig.java:34,60`이 `app.rate-limit.default-policy-id`로 검증. env 키 `APP_RATE_LIMIT_DEFAULT_POLICY_ID`는 그대로(`env-keys.yaml`·`.env.example` 변경 없음). `RedisCapabilityCompositionTest.aDefaultPolicyTheLimiterDoesNotHaveIsRefusedAtStartup` FAIL(`Expecting actual not to be null`)→PASS | - | 읽는 쪽 하나만 남기고 다른 키 삭제(sample의 `ca-skeleton.rate-limit.*`는 1차 L-11) |
| S6-#7 | Required | sample이 bootstrap 인프라를 복사, 이미 갈라짐 | 남음 | `SP/bootstrap/{tracing,idempotency,settings,logging,metrics,context,management}` 525줄. `SampleTracingSampleRateResolver.java:23` `"staging" -> 0.10`, `SampleIdempotencyConfig.java:15` "stand-in", `SamplePseudonymizationConfig.java:12` "Sample-local copy" | W3 | 소유자 결정대로 멱등성 executor·outbox relay 조립을 `composition:*` 모듈로 옮겨 두 root가 함께 쓰고, tracing·logging·metrics·context·management는 공용 library leaf로(registry edge 추가), staging 분기 삭제 |
| S6-#7 | Required | sample이 bootstrap 인프라를 복사, 이미 갈라짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **새 leaf `composition:service-runtime`**(`dev.caskeleton.composition.runtime`, edge application-core, shared-contract, adapter-outbound-support, adapter-outbound-identifier):<br>- 원본을 app-bootstrap에서 옮겼다: `tracing`(TracingConfig 외 5), `metrics`(MetricsContractConfig+filter 2), `context`(DomainContextConfig/Settings), `logging`(PseudonymizationConfig, PrivacySettings), `management/security`(ManagementSecurityConfig).<br>- 모두 이 모듈의 `AutoConfiguration.imports`로, sampling bridge는 `spring.factories`로 등록한다.<br>- app-bootstrap과 sample이 `runtimeOnly project(':composition:service-runtime')`를 쓴다.<br>**sample:** 복사본 10개와 `spring.factories`를 삭제했다. 원본을 쓰므로 `staging=0.10` 분기도 사라졌다.<br>**sample actuator chain:** 복사본이 아니라 공개 데모라는 샘플만의 결정이라 남겼다. bean 이름을 `actuatorSecurityFilterChain`으로 바꿔 공용 chain이 물러나게 했다(`ConditionalOnMissingBean(name)`).<br>**테스트:** `ServiceRuntimeRegistrationTest` 4개(신규), 옮긴 테스트 9 클래스 — `:composition:service-runtime:test` 86 PASS. `ActuatorSecurityHttpTest`, `DefaultCompositionBootTest`, `StartupOrderContractTest`, `ConfigurationNamespaceContractTest` 갱신 후 PASS. | - | 소유자 결정대로 멱등성 executor·outbox relay 조립을 `composition:*` 모듈로 옮겨 두 root가 함께 쓰고, tracing·logging·metrics·context·management는 공용 library leaf로(registry edge 추가), staging 분기 삭제 |
| S6-#8 | Required | sample root가 다른 leaf 패키지를 넓게 scan | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `SamplePortfolioApplication`: `@ComponentScan("dev.caskeleton.sample")`·`@ConfigurationPropertiesScan("dev.caskeleton.sample")`, 제외는 `WebSecurityAutoConfiguration` 하나(`SamplePortfolioApplication.java:31-32`). web·objectstorage는 각 auto-config로. `SamplePublicAccessSecurityConfigTest.sampleCompositionRootExcludesOnlyTheWebSecurityRoot`·`sampleCompositionRootScansOnlyTheSamplePackage`(옛 exclude-filter 단언 대체). sample `test`·`integrationTest` 51·`systemTest` 3·`webSystemTest` 5 PASS | - | scan을 `dev.caskeleton.sample`로 좁히고 web·identifier·objectstorage는 각 leaf auto-config로 받기(보안 설정 2개는 exclude/property로 끔) |
| S6-#9 | Required | sample `application.yml` 중 읽는 코드 없는 블록 | 남음 | 326줄 중 약 101줄: `src/sample-portfolio/src/main/resources/application.yml:150-177`(capabilities.cache), `:180-181`(bootstrap), `:210-226`(logging), `:255-279`(app.cache.redis), `:280-283`(messaging), `:284-288`(notification), `:289-308`(outbound.http). sample classpath에 해당 binder 없음(`src/sample-portfolio/build.gradle:48-83`) | W5 | 해당 블록 삭제 |
| S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 남음 | poster 관련 main 약 5.9k줄 vs WorkLog 약 2.2k줄. `SP/application/`에 `command/query/event/port/exception`과 `poster/posterimage/worklog` 공존<br>Wave 3 W3-P25: 미완 — 이유: 기능별 패키지 재배치와 poster-image 별도 sample 모듈 분리는 sample 전체 파일 이동(+`modules.json` leaf 등록)이라, 동시에 도는 P18(sample outbox·멱등성·`PosterEventPublisher`)·P24(object storage)와 같은 파일을 대량으로 겹친다. 통합 뒤 단독 작업으로 넘김. 이번 묶음에서 legacy 모드 삭제(S6-#10b)로 poster 표면은 줄었다 | W3 | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 |
@@ -1002,7 +1002,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S6-G3 | 권고 | capability 하나 켜는 표면이 큼(outbox 스위치 5개, yml 19개) | 완료 | bootstrap yml 19개 1,388줄 → 9개 655줄. Outbox+relay = build 줄 2개 + `APP_OUTBOX_ENABLED`·`APP_OUTBOX_RELAY_ENABLED`(`CS:35`), 검증 클래스 1개(`OutboxCanonicalTransportRequirementValidator`); Redis 연결 env는 `src/adapter/outbound/cache-redis/README.md:50`에 문서화 | - | - |
| S6-lead-1 | 권고 | gRPC 서버 스택 2개, 둘 다 조립 안 됨 (= X1-#10) | 완료 | `adapter:inbound:grpc`는 자기 imports(`GrpcServerConfig`)로 한 줄 선택(`CS:42`), 플랫폼 `grpc:*`는 별도 build `src/optional-platforms`(`CS:41`). 두 스택 공존은 X1-#10에서 의도로 수용 | - | - |
| S6-lead-2 | 권고 | 인라인 `TransactionPort` fake가 저장소 전체에 (= X1-#3) | 남음 | 인라인 fake 24 → 10개 파일: application-core 4(`TransactionPortTest` 포함), application-notification 4, `application-fileserver/.../testkit/DirectTransactions.java`, `composition/fileserver-platform/.../FileserverAssemblyFixture.java`. `DirectTransactionPort` 사용 12개 파일 | W4 | 계약 자체를 검증하는 `TransactionPortTest` 외 9개를 `DirectTransactionPort`로 교체 |
| S6-lead-3 | 권고 | 복사용 예제 `CreateWorkLogUseCase`가 `LegacyOutboxAppendPort` 사용 (= X1-#1 append 포트) | 남음 | `SP/application/worklog/CreateWorkLogUseCase.java:7`; canonical `OutboxAppendPort`(`src/application-core/src/main/java/dev/caskeleton/application/outbox/OutboxAppendPort.java:13`) 존재, legacy 포트 Javadoc은 "cutover 창 동안만"(`LegacyOutboxAppendPort.java:3-9`)<br>Wave 1–2 P1: 미완 — 이유: sample을 `OutboxAppendPort`로 옮기려면 `ValidatedIntegrationEvent`를 만들 encoder가 있어야 하는데 템플릿에 없다(`IntegrationEventEncoderPort` 구현 0). 결정 7(템플릿 JSON encoder 제공 + legacy 포트 삭제)이 Wave 3 3-C 작업. sample의 legacy 포트 사용처 3곳(`CreateWorkLogUseCase`, `PosterEventPublisher`, `PosterImagePublicationEventPublisher`) | W2 | 예제를 `OutboxAppendPort` + `ValidatedIntegrationEvent`로 옮기고 MSG-015 cutover 후 legacy 포트 삭제 |
| S6-lead-3 | 권고 | 복사용 예제 `CreateWorkLogUseCase`가 `LegacyOutboxAppendPort` 사용 (= X1-#1 append 포트) | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **이전:** sample 3곳(`CreateWorkLogUseCase`, `PosterEventPublisher`, `PosterImagePublicationEventPublisher`)을 `PortfolioEventOutbox`로 옮겼다(`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PortfolioEventOutbox.java:44`). 이 클래스는 `OutboxAppendPort`와 `IntegrationEventEncoderPort`를 쓴다.<br>**계약 등록:** `PortfolioEventContracts`가 계약 8개(poster 7 + `portfolio.worklog.reserved` v1)와 schema hash를 등록한다.<br>**삭제:** `LegacyOutboxAppendPort`.<br>**테스트:** `PortfolioEventOutboxTest`, `PortfolioEventContractsTest`, `CreateWorkLogOutboxTest`, `PosterEventPublisherTest`, `WorkLogReservedConsumerDedupeContractTest` PASS. `:sample-portfolio:test` 289, integrationTest 49, systemTest 3, webSystemTest 5 모두 PASS. | - | 예제를 `OutboxAppendPort` + `ValidatedIntegrationEvent`로 옮기고 MSG-015 cutover 후 legacy 포트 삭제 |
| S6-lead-4 | 권고 | `CS` WIRED=yes vs `dependencyPolicy` 모순, `MasterSwitch`가 없는 capability 나열 | 해당 없음(코드 삭제) | `dependencyPolicy`·`MasterSwitch` 삭제(`CS:248`), WIRED 정의를 "선택하면 조립됨"으로 재정의(`CS:11`, `CS:37`) | - | - |
| S6-lead-5 | 권고 | `DefaultUploadApplicationService` 생성자 14개 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `f2ff284a`. `DefaultUploadApplicationService` 생성자(`upload/DefaultUploadApplicationService.java:76`) 14개 → 10개: `UploadStores(metadata, sessions, cleanupQueue)`·`UploadPolicies(access, filenames, upload)` record | - | 정책 3개(access·filename·upload)와 저장소 2개를 record로 묶거나 업로드 단계별 서비스로 분해 |
| S7-#1a | Required | 선택 불가·SDK 없는 messaging leaf(experimental 4, rabbit 2)와 Debezium | 해당 없음(코드 삭제) | `CS:124-130` | - | - |
@@ -1012,12 +1012,12 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S7-#3 | Required | grpc 18 leaf를 9 leaf로 | 완료 | Wave 3 W3-P17 (Wave 3 라운드 1 커밋): `e2397d2f`. registry의 `optional-grpc` leaf 18 → 9: `grpc-core-api`, `grpc-runtime`(policy+server+client+discovery+admin), `grpc-contract`(proto-contract+codegen 자리), `grpc-observability`, `grpc-operation-ledger-jpa`, `grpc-spring-boot-starter`, `grpc-testkit`, `grpc-advanced`(bootstrap+edition+streaming+resilience+diagnostics), `grpc-advanced-compat`. 패키지 이름은 그대로(import 변경 없음). settings는 registry 구동(`OptionalArchitectureRegistrySettingsPlugin`)이라 `src/optional-platforms/settings.gradle` 변경 불필요, build-logic 무변경. 새 edge 없음, 미사용 edge 삭제: grpc-client의 io.grpc(leaf 합병으로 소멸), codegen→proto-contract, edition→core-api/proto-contract/bootstrap, testkit→proto-contract/codegen. starter·grpc-advanced·compat는 grpc-runtime의 versionless io.grpc api를 받으므로 `ca.grpc-platform-module`(gRPC BOM)로 전환 — 새 leaf로 lockfile을 재생성할 때 BOM 없이 `Could not find io.grpc:grpc-api:.`로 실패해서다(기존 lockfile 값과 동일하게 해석됨). `GrpcPackageOwnershipTest` leaf 목록 갱신. lockfile은 `-p optional-platforms resolveAndLockAll --write-locks`로 재생성 | - | policy+server+client+discovery+admin → `grpc-runtime`, proto-contract+codegen → `grpc-contract`, advanced 5개 → `grpc-advanced`, 미사용 edge 삭제 |
| S7-#4 | Required | gate·guard·catalog 같은 governance를 운영 코드로 (≈ N-9) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): 삭제 커밋 `9b296c7c`(P5 D). 상수 gate·guard·catalog·invariant·testkit·문자열 ArchUnit 흉내 삭제(아래 「제거된 코드」). 전부 main 호출자 0이었다. `GrpcRawApiImportRule`·`GrpcApplicationBoundaryRules`는 자기 테스트의 합성 입력만 검사하고 저장소 코드를 검사하지 않아서 테스트로 옮기지 않고 삭제했다(inbound→outbound 규칙은 app-bootstrap ArchUnit `INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS`가 이미 검사). `GrpcResolverSafetyPolicy`는 상수 메서드 2개만 삭제. starter의 항상 통과하던 advanced 격리 검사도 함께 제거 `src/grpc/grpc-spring-boot-starter/src/main/java/dev/caskeleton/grpc/boot/GrpcPlatformStartupValidator.java:41`. 문서 갱신: `src/grpc/CLAUDE.md`, `src/grpc-advanced/CLAUDE.md`, `docs/runbooks/grpc-advanced-capabilities.md`, `docs/compatibility/grpc-advanced-support-matrix.md` | - | 상수 gate·catalog·invariant·testkit 삭제, import 규칙은 ArchUnit 테스트로 |
| S7-#5a | Required | `messaging-outbox-jdbc-postgresql`의 Debezium 4개 | 해당 없음(코드 삭제) | `CS:130` | - | - |
| S7-#5b | Required | 한 leaf가 relay 로직·PG repository·admin journal을 함께 가짐 | 남음 | `src/messaging/messaging-outbox-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/`: relay 7클래스 877줄, `JdbcOutboxRepository` 721줄, `JdbcAdminOperationJournal` 326줄; Spring JDBC import 파일 2개. inbox는 6개 중 5개가 stdlib | W3 | `messaging-reliability`(stdlib relay·inbox 로직) + `messaging-reliability-jdbc-postgresql`(Jdbc 3종)으로 재분할 |
| S7-#5b | Required | 한 leaf가 relay 로직·PG repository·admin journal을 함께 가짐 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **`messaging-reliability`**(stdlib: `OutboxRelay`·`OutboxRelayWorker`·`OutboxRetryScheduler`·`OutboxEnvelopeFactory`·`OutboxCleanupJob`·`OutboxProperties`·`OutboxRelayReport`, `IdempotentConsumer`·`TransactionalInboxHandler`·`InboxCleanupJob`·`InboxOutcome`·`InboxRetentionPolicy`).<br>**`messaging-reliability-jdbc-postgresql`**(`JdbcOutboxRepository`, `JdbcInboxRepository`, `JdbcAdminOperationJournal`, migration `V1001..V1005`·`V1101`, PG IT 3개).<br>**영향:** 옛 두 leaf는 삭제했다. 패키지명은 그대로라 starter 코드는 바뀌지 않았다. CI lane `integration-main.yml`을 새 경로로 바꿨다.<br>**테스트:** `:messaging:messaging-reliability:test` 47, `:messaging:messaging-reliability-jdbc-postgresql:test` 8, integrationTest 36, starter test 87, integrationTest 3 PASS. | - | `messaging-reliability`(stdlib relay·inbox 로직) + `messaging-reliability-jdbc-postgresql`(Jdbc 3종)으로 재분할 |
| S7-#6a | Required | `PublishResult` 7인자 생성자 직접 호출 | 남음 | 11파일 28회 → 5파일 8회(`KafkaMessagingTransport` 1, `KafkaPublishFailureClassifier` 2, `KafkaPublishMapper` 1, `DefaultMessagePublisher` 2, `MS/PublishResults.java` 2). `PublishResult.java:30`에 정적 factory 없음 | W3 | `PublishResult.rejected/ambiguous/confirmed` 정적 factory 추가 후 8곳 교체 |
| S7-#6b | Required | `PublishEvidence.ambiguous()`를 두고 직접 생성 | 남음 | `MS/PublishResults.java:43-47,57-59` `new PublishEvidence(true, MAY_HAVE_BEEN_TRANSMITTED, false, NONE)` 2회 | W3 | `PublishEvidence.ambiguous()` 사용 |
| S7-#6c | Required | `rejectedLocally` 4벌, `PulsarPreSendRejection`·`NatsPreSendRejection` 중복 | 해당 없음(코드 삭제) | rabbit·pulsar·nats 삭제(`CS:124-129`), 남은 것은 `KafkaMessagingTransport.java:200` 1개 | - | - |
| S7-#7 | Required | envelope ↔ canonical header 변환 3벌 | 해당 없음(코드 삭제) | Rabbit mapper·Debezium router 삭제(`CS:128,130`). 남은 Kafka `KafkaHeaderMapper`(쓰기)·`KafkaDeliveryMapper`(읽기) 한 쌍, `RESERVED_HEADER_FORGED`는 `KafkaHeaderMapper.java:92` 한 곳 | - | - |
| S7-#8 | Consider | outbox port·repository 죽은 표면 | 남음 | `OutboxRepository.java:36` `leaseBatch`(main 호출 0), 4인자 `claimBatch`(`:47`)·3인자 `markAmbiguous`(`:69`)(relay는 `:58`·`:72` 오버로드만 사용), `JdbcOutboxRepository.java:426-455` `*Unfenced` 4개(호출 0), 손 JSON `:608-680` | W3 | 메서드 7개 삭제, header JSON은 Jackson 또는 `jsonb_each_text` (purge 오버로드는 1차 M-6) |
| S7-#8 | Consider | outbox port·repository 죽은 표면 | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** `OutboxRepository`의 `leaseBatch`, 4인자 `claimBatch`, 3인자 `markAmbiguous`(`src/messaging/messaging-reliability-api/src/main/java/dev/caskeleton/messaging/reliability/OutboxRepository.java:43`, `:57`만 남음). `JdbcOutboxRepository`의 LEASE SQL, `*Unfenced` 4개, `update` helper, 손으로 쓴 JSON(`toJson`/`fromJson`/`escape`/`unescape`).<br>**header 저장:** `jsonb_object(?::text[])`로 쓰고 `jsonb_each_text`로 읽는다(`src/messaging/messaging-reliability-jdbc-postgresql/src/main/java/dev/caskeleton/messaging/outbox/JdbcOutboxRepository.java:59`, `:77-78`).<br>**TDD:** `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader`(`OutboxPostgresIT.java:612`)가 먼저 FAIL했다("map entries not expected: x-path=C:\exports\"") → 수정 후 PASS. integrationTest 36/36.<br>**그대로 둔 것:** purge 오버로드(1차 M-6)는 손대지 않았다. | - | 메서드 7개 삭제, header JSON은 Jackson 또는 `jsonb_each_text` (purge 오버로드는 1차 M-6) |
| S7-#9a | Consider | starter 550줄 god config | 남음 | `MS/MessagingCoreAutoConfiguration.java` 549줄, `@Bean` 28 | W3 | config/validation, publish pipeline, observability 세 configuration으로 분리 |
| S7-#9b | Consider | broker 중립 core starter에 broker 전용 필드 union | 남음 | Rabbit 필드는 삭제(`CS:235`), `MS/BrokerSettings.java:32-44`에 Kafka 전용 필드(`bootstrapServers`, `enableIdempotence`, `acks` 등) 남음 | W3 | Kafka 필드는 starter-kafka가 자기 settings record로 바인딩 |
| S7-#9c | Consider | 외부 사용 0인 Blocking/Reactive/Batch facade와 `reactor-core` api 노출 | 남음 | `MS/Default{Blocking,Reactive,Batch}MessagePublisher.java`, `MS/ReactiveMessagePublisher.java`(합계 398줄) starter 밖 main 참조 0; `src/messaging/messaging-spring-boot-starter/build.gradle:46` `api 'io.projectreactor:reactor-core'` | W3 | facade 삭제(또는 reactor `compileOnly`) |
@@ -1033,7 +1033,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S7-#16c | Nit | `KafkaConsumerRegistrar.dispatch` 긴 메서드 | 남음 | `KafkaConsumerRegistrar.java:264-354`(약 90줄) | W5 | S7-#2 결정 후: 유지면 분해, 삭제면 소멸 |
| S7-lead-1 | 권고 | outbox relay 3개 (= X1-#1) | 완료 | V2 relay 삭제(`CS:175`), 앱 relay는 `PublishPendingOutboxEventsUseCase` 하나(`BS/autoconfigure/outbox/OutboxConfig.java:86`). messaging `OutboxRelay`는 vendored 제품 기능으로 `@ConditionalOnBean(OutboxRepository)`(`MS/MessagingReliabilityAutoConfiguration.java:81`)이고 main에 `JdbcOutboxRepository` 생성 0이라 앱 조립에 들어오지 않음, `6d27356e` | - | - |
| S7-lead-2 | 권고 | 멱등성 저장소 3개(앱, grpc ledger, messaging inbox) (= X1-#2) | 남음 | 셋 다 존재. messaging inbox는 소비자 dedup이고 family 규칙상 앱 계약 사용 불가(`CLAUDE.md:65`); grpc ledger도 앱 edge 없음(`MJ:606`, allowed `grpc-core-api`만) → 분리는 구조상 의도. 그러나 root `CLAUDE.md:59-67` family 표에 `grpc:*`·`grpc-advanced:*` 행이 없어 이 예외가 문서에 없음 | W5 | family 표에 gRPC 플랫폼을 messaging과 같은 vendored 예외(자체 ledger, optional build)로 한 줄 추가 |
| S7-lead-3 | 권고 | Kafka producer 경로 2개 (= X1 표 Kafka producer) | 남음 | R0 `LegacyKafkaMessagingRootAutoConfiguration`·`KafkaSender`·`KafkaSenderAutoConfiguration`(`src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/`) vs 플랫폼 `KafkaMessagingTransport`; `CS:32` "legacy `KafkaSender` seam and the vendored platform"<br>Wave 1–2 P1: 미완 — 이유: = X1 표 Kafka producer(legacy `KafkaSender` R0 경로). 결정 7로 Wave 3 3-C에서 경로째 삭제. 이번 묶음 지시대로 legacy seam은 손대지 않음 | W2 | MSG-015 cutover(S6-lead-3과 함께) 후 R0 `KafkaSender` 경로 삭제 |
| S7-lead-3 | 권고 | Kafka producer 경로 2개 (= X1 표 Kafka producer) | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): R0 경로(`LegacyKafkaMessagingRootAutoConfiguration`·`KafkaSender`·`KafkaSenderAutoConfiguration`·`KafkaMessageBroker`)를 `6268c494`에서 삭제했다. 남은 Kafka producer는 platform `KafkaMessagingTransport` 하나다. | - | MSG-015 cutover(S6-lead-3과 함께) 후 R0 `KafkaSender` 경로 삭제 |
| S7-lead-4 | 권고 | lease/claimBatch 구현 여러 벌 (= X1-#6) | 남음 | persistence-jpa 안에 owner+token lease 2벌: outbox(`OutboxStoreAdapter.java:79-90`, `OutboxEventJpaRepository.java:34,47`)와 알림(`RecipientDeliveryJpaRepository.java:85-175`, `JpaRecipientLeaseStore`). outbox는 계약 kit `OutboxLeaseFencingContract`(application-core testFixtures)가 있으나 `RecipientLeaseStorePort`는 PG 통합 테스트 1개뿐. messaging `OutboxRepository.claimBatch`는 vendored라 별개 | W4 | SQL은 테이블별 유지(X1-#6), application-notification testFixtures에 `RecipientLeaseFencingContract`를 만들어 fake와 JPA store가 함께 상속 |
| S7-lead-5 | 권고 | messaging 기본 off 처리 두 곳(sentinel vs starter switch) | 해당 없음(코드 삭제) | `DisabledMessagingSentinelAutoConfiguration` 삭제(`CS:240`), 끄는 키는 모듈 `app.messaging.enabled` 하나(`CS:32`) | - | - |
@@ -1053,10 +1053,10 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
|---|---|---|---|---|---|---|
| NEW-1a | Consider | compose smoke가 lane이 실제로 켠 기능·DB 벤더를 확인하지 않는다. `expectedSwitchesOn`·`expectedPersistenceVendor`를 읽는 코드가 없다(스크립트·정적 검사기 모두). | 완료 | Wave 1–2 P13 (fcddab7e·Wave 2 커밋): 방식: Spring Boot `management.info.env.enabled=true`(`src/app-bootstrap/src/main/resources/config/observability.yml:86-94`, `info.*` 트리만 노출, env 전체 아님)와, 각 capability 모듈이 자기 설정 파일에 `info.capabilities.<name>.enabled: ${<스위치 키>:<auto-config의 matchIfMissing과 같은 기본값>}`을 싣는다. JPA는 `vendor: ${ca-skeleton.persistence.vendor:postgresql}`도 싣는다(vendor=postgresql이면 `JpaDataSourceProfileValidator`가 실제 DB가 PostgreSQL인지 기동 때 확인하므로 선택자=실제 DB). Java 코드 추가 없음, capability 모듈 8개의 yml만 추가: `persistence-jpa.yml`, `persistence-mongo/config/mongo.yml`, `messaging-kafka/.../messaging.yml`, `notification-platform/.../notification.yml`, `graphql/config/graphql.yml`, `cache-redis.yml`, `fileserver-platform/.../fileserver.yml`, `httpclient.yml`. 계약 재정의: `expectedSwitchesOn`(property 키) → `expectedCapabilitiesOn`(info 이름), 최상위 `capabilities` 카탈로그(8개) 추가, `$activationComment`/`$vendorComment` 갱신(`src/config/runtime/compose-profile-contracts.json:741-752`). smoke: `scripts/run-compose-runtime-smoke.sh:434-468` — health 응답 뒤 `/actuator/info`를 받아 ①보고된 capability 이름 집합 = 카탈로그(모듈 누락·info 꺼짐 검출, all-off lane이 빈 목록끼리 비교하는 헛검사가 안 되게) ②enabled=true 집합 = `expectedCapabilitiesOn` ③JPA가 켜졌으면 `vendor`, 아니면 `none` = `expectedPersistenceVendor`. 정적 검사 `scripts/verify-compose-profile-contracts.sh:133-146`(check 6): 카탈로그 밖 이름, JPA 켜짐/꺼짐과 맞지 않는 vendor를 거부. 실제 실행(Docker, qualification 이미지): 재현 — off-local이 persistence-jpa를 기대하도록 바꾼 계약에서 HEAD의 smoke는 `all 1 blocking lanes passed`(결함), 새 smoke는 `off-local: the application reports [] on, the contract expects [persistence-jpa]`로 FAIL. 실제 계약: `--lane off-local` passed(8개 모두 `enabled:"false"`), `--lane local-jpa` passed(`persistence-jpa {enabled:"true",vendor:"postgresql"}`), `--lane off-prod` passed. `--lane local-redis`는 info 검사(`redis enabled:"true"`)를 통과한 뒤 기존 3c 기동 로그 검사에서 실패(P13-new-2). 정적 검사: 실제 계약 18 lane 전부 match, 깨진 사본(카탈로그 밖 이름·JPA 켜짐+vendor none)은 두 lane FAIL. 한계: objectstorage·websocket·gRPC는 모든 lane에서 꺼지고 info에 보고하지 않는다(예전 activation endpoint도 보고하지 않던 셋). `ConfigurationNamespaceContractTest`의 허용 root에 프레임워크 namespace `info` 추가(`app-bootstrap/src/test/.../ConfigurationNamespaceContractTest.java:57-74`). | - | 결정(2026-09-25): smoke가 lane이 켠 capability·DB 벤더를 health component(또는 info)로 확인, 계약 필드를 그 값에 맞춰 재정의 |
| NEW-1b | Required | 새 CI 잡이 GitHub에서 한 번도 돌지 않았다. 18개 lane을 실제로 돌린 증거가 없다. | 남음 | 브랜치에 upstream이 없고(`git status -sb` → `## refactor/review-followup`), `6d27356e`를 포함한 원격 브랜치도 없다(`git branch -r --contains` 결과 비어 있음). 새로 추가된 잡은 `.github/workflows/build-logic.yml:30-41`(included build 테스트), `.github/workflows/integration-main.yml:64`(`main-check`), `:85`(`configuration-cache`), `:130`(`jpa-candidate-evidence`)이다. compose 잡은 `integration-main.yml:374-387`에 있고 `push: main`·nightly·dispatch에서만 돈다(`:33-40`). 계약 lane은 18개다(`jq '.lanes\|length'`). lane은 `COMPOSITION=qualification` 이미지로 돈다(`run-compose-runtime-smoke.sh:34`, `src/Dockerfile:70-77`). | W4 | 로컬에서 돌리려면 docker, docker compose 2.24.4 이상(`compose-profile-contracts.json`의 `minimumComposeVersion`), jq, openssl(TLS lane의 인증서 생성, `:183-211`)이 필요하다. 명령은 `bash scripts/run-compose-runtime-smoke.sh --matrix src/config/runtime/compose-profile-contracts.json`이고, 이미지는 스크립트가 `docker compose build app`으로 만든다(`:366`). 스크립트의 도구 사전 검사(`:75-77`)에 `openssl`을 추가한다. 브랜치를 push해서 `workflow_dispatch`로 `integration-main`·`build-logic`을 한 번 돌리고 그 결과를 증거로 남긴다. |
| NEW-2a | Consider | outbox relay 조립이 app-bootstrap에 있다. | 남음 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java:44-120`. 조건: `@AutoConfiguration(afterName=PersistenceJpaAutoConfiguration, MessagingBridgeRootAutoConfiguration)`, `@ConditionalOnProperty(ca-skeleton.outbox.enabled=true)`, `@ConditionalOnBean(OutboxStorePort)`, `@EnableScheduling`. 빈: `outboxCanonicalTransportRequirementValidator`, `outboxRelayScheduler`(`relay-enabled` 기본 true + `@ConditionalOnBean(OutboxMessagePublishPort)`), `outboxRandomGenerator`, `outboxLeaderElection`, `outboxMetrics`. 같은 패키지에 `OutboxSettings`·`OutboxMetrics`·`OutboxRelayScheduler`·`OutboxLeaderElectionToken`·`OutboxCanonicalTransportRequirementValidator`가 있다. 등록은 `src/app-bootstrap/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:2`. persistence-jpa로 옮기지 못하는 이유는 `AdapterBoundaryArchitectureTest.java:207-227` 때문이다. 이 규칙은 `adapter.outbound.persistence..` 패키지가 `*UseCase`를 참조하는 것을 막는데, `OutboxConfig`는 `PublishPendingOutboxEventsUseCase`를 직접 만든다(:85). | W3 | 새 leaf `:composition:outbox-relay`(패키지 `dev.caskeleton.composition.outbox`)를 만들고 위 6개 클래스와 테스트(`OutboxConfigTest`·`OutboxSettingsTest`·`OutboxRelaySchedulerLoggingTest`·`OutboxCanonicalTransport*Test`)를 옮긴다. 자세한 내용은 아래 메모. |
| NEW-2b | Consider | 멱등성 executor 조립이 app-bootstrap에 있고, sample이 검증 없는 복사본을 따로 가진다. | 남음 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencyProviderSelectionConfig.java:28-56`: `@AutoConfiguration`, 빈은 `idempotencyExecutor` 하나다(`@ConditionalOnExpression(provider != disabled)`). store가 정확히 1개가 아니면 기동 실패한다(:39-47). 설정은 `IdempotencySettings.java:24-67`에 있고 lease·TTL 상한과 codec·revision을 검증한다. sample 복사본 `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/idempotency/SampleIdempotencyConfig.java:21-47`과의 차이는 셋이다. ① `Binder`로 직접 읽어서 상한·양수 검증이 없다(:38-45). ② store를 1개로 가정한다(`IdempotencyStorePort store` 직접 주입). ③ `Clock` 빈과 `@EnableScheduling`을 함께 들고 있다(:22,:27-30). | W3 | 새 leaf `:composition:idempotency`로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`와 테스트(`IdempotencyProviderCompositionTest`·`IdempotencySettingsTest`)를 옮긴다. sample은 `runtimeOnly project(':composition:idempotency')`를 쓰고 `SampleIdempotencyConfig`에서는 executor 빈을 지운다(Clock·scheduling만 남긴다). modules.json의 `sample-portfolio.allowed_dependencies`에 `composition-idempotency`를 추가한다. |
| NEW-2a | Consider | outbox relay 조립이 app-bootstrap에 있다. | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): X1-#1i와 같다. 조립은 `src/composition/outbox-relay/src/main/java/dev/caskeleton/composition/outbox/OutboxRelayAutoConfiguration.java:43-53`에 있고, app-bootstrap `AutoConfiguration.imports`에서 outbox 줄을 뺐다. | - | 새 leaf `:composition:outbox-relay`(패키지 `dev.caskeleton.composition.outbox`)를 만들고 위 6개 클래스와 테스트(`OutboxConfigTest`·`OutboxSettingsTest`·`OutboxRelaySchedulerLoggingTest`·`OutboxCanonicalTransport*Test`)를 옮긴다. 자세한 내용은 아래 메모. |
| NEW-2b | Consider | 멱등성 executor 조립이 app-bootstrap에 있고, sample이 검증 없는 복사본을 따로 가진다. | 완료 | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **이동:** `IdempotencyProviderSelectionConfig`→`IdempotencyAutoConfiguration`(`src/composition/idempotency/src/main/java/dev/caskeleton/composition/idempotency/IdempotencyAutoConfiguration.java:38`, executor 생성 `:58`).<br>**설정:** `IdempotencySettings.bind`는 `StrictSettingsBinder.bindExcept`로 strict 바인딩한다. `config/module-defaults/idempotency.yml`로 옮겼다(예전 `capabilities.yml`).<br>**sample:** `SampleIdempotencyConfig`를 삭제했다. Clock·`@EnableScheduling`만 `SampleSchedulingConfig`에 남겼다.<br>**테스트:** `IdempotencySettingsTest`(strict), `IdempotencyAutoConfigurationTest`, `IdempotencyModuleDefaultsTest`, `StrictSettingsBinderTest`, `SampleIdempotencyReplayIntegrationTest` PASS. | - | 새 leaf `:composition:idempotency`로 `IdempotencyProviderSelectionConfig`·`IdempotencySettings`와 테스트(`IdempotencyProviderCompositionTest`·`IdempotencySettingsTest`)를 옮긴다. sample은 `runtimeOnly project(':composition:idempotency')`를 쓰고 `SampleIdempotencyConfig`에서는 executor 빈을 지운다(Clock·scheduling만 남긴다). modules.json의 `sample-portfolio.allowed_dependencies`에 `composition-idempotency`를 추가한다. |
| NEW-3 | Required | fileserver 보상 트랜잭션의 30초 타임아웃이 사라졌다. 지금은 `inNew` 경로 전체에 타임아웃이 없다. | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): C-3d와 같은 수정·테스트. `SpringTransactionPort.java:62` | - | 가장 작은 변경은 `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/SpringTransactionPort.java`의 `requiresNewTemplate`에 `setTimeout(30)`을 거는 것이다(상수 1개). 이러면 보상·outbox·audit용 REQUIRES_NEW의 옛 동작이 돌아온다. 전 트랜잭션에 상한을 원하면 대신 `persistence-jpa.yml` module-defaults에 `spring.transaction.default-timeout: 30s`를 둔다. 테스트는 `SpringTransactionPort` 단위 테스트에서 inNew template의 timeout 값을 단언한다. |
| NEW-4a | Required | Kafka legacy seam producer에 보안 설정이 전혀 없다(항상 PLAINTEXT). | 남음 | `src/adapter/outbound/messaging-kafka/src/main/java/dev/caskeleton/adapter/outbound/messaging/kafka/KafkaSenderAutoConfiguration.java:62-80`: bootstrap·serializer·acks·timeout만 넣는다. `security.protocol`·SASL·SSL 키가 없다. messaging-kafka 모듈을 고르면 `LegacyKafkaMessagingRootAutoConfiguration`(imports 1행)로 항상 켜진다. 반면 platform producer는 `KafkaSecurityConfigurer`를 적용한다(`KafkaMessagingAutoConfiguration.java:234-235`). | W1 | seam producer도 같은 보안 profile을 쓰게 한다. `KafkaMessagingAutoConfiguration.producerSecurity(...)`를 재사용 가능한 static으로 빼거나 `KafkaSecurityConfigurer` 결과를 주입받아 `config.putAll(...)`한다. 보안 profile이 없고 broker가 TLS·auth를 요구하면 기동을 실패시킨다(platform 쪽 `:200-211`과 같은 규칙). 장기적으로는 seam을 platform transport로 합쳐 producer를 하나로 줄인다. |
| NEW-4a | Required | Kafka legacy seam producer에 보안 설정이 전혀 없다(항상 PLAINTEXT). | 해당 없음(코드 삭제) | Wave 3 W3-P18 (Wave 3 라운드 2 커밋): **삭제:** 항상 PLAINTEXT인 seam producer(`KafkaSenderAutoConfiguration.java:62-80`)와 그것을 켜던 `LegacyKafkaMessagingRootAutoConfiguration`이 `6268c494`에서 삭제됐다. messaging-kafka의 `AutoConfiguration.imports`도 삭제했다.<br>**남은 producer:** platform producer 하나다(`KafkaMessagingAutoConfiguration.java:188`, `:216`). 보안 profile이 없는데 broker가 TLS를 요구하면 기동을 거부하는 규칙도 그 경로에 그대로 있다.<br>**테스트:** `KafkaCapabilityActivationTest`는 leaf가 bridge+starter 묶음이 된 것에 맞게 갱신했고 PASS다. | - | seam producer도 같은 보안 profile을 쓰게 한다. `KafkaMessagingAutoConfiguration.producerSecurity(...)`를 재사용 가능한 static으로 빼거나 `KafkaSecurityConfigurer` 결과를 주입받아 `config.putAll(...)`한다. 보안 profile이 없고 broker가 TLS·auth를 요구하면 기동을 실패시킨다(platform 쪽 `:200-211`과 같은 규칙). 장기적으로는 seam을 platform transport로 합쳐 producer를 하나로 줄인다. |
| NEW-4b | Required | Kafka TLS 자료(truststore/keystore) 설정 키가 없다. `MUTUAL_TLS`를 설정 값으로는 받지만 실제로 동작하지 않는다. | 완료 | Wave 1–2 P1 (fcddab7e·Wave 2 커밋): M-2e 행과 같은 수정·테스트 | - | `BrokerSettings`(messaging-spring-boot-starter)에 `trust-store-location/password/type`, `key-store-location/password/type`을 추가하거나 Spring Boot SSL bundle 이름(`ssl-bundle`)을 받는다. `KafkaSecurityConfigurer`가 `ssl.truststore.*`·`ssl.keystore.*`(또는 PEM `ssl.*.certificates`)를 채운다. keystore가 없는 `MUTUAL_TLS`는 컴파일 단계에서 거부한다. 구현하지 않을 거면 `MessagingConfigurationCompiler.java:258`에서 `MUTUAL_TLS`를 뺀다. |
| NEW-4c | Consider | platform producer가 broker 주소를 `spring.kafka.bootstrap-servers`에서만 읽고, 선언된 broker의 `bootstrap-servers`는 검증만 한 뒤 쓰지 않는다. | 완료 | Wave 1–2 P1 (fcddab7e·Wave 2 커밋): M-2b 행과 같은 수정·테스트 | - | 주소 출처를 하나로 정한다. 추천은 compiled broker(`CompiledMessagingConfiguration`의 kafka broker `bootstrapServers()`)를 쓰고, 없을 때만 `spring.kafka.bootstrap-servers`로 fallback하는 것이다. 둘 다 있는데 값이 다르면 기동을 실패시킨다. 테스트는 `producerConfig(...)`에 두 값을 다르게 주고 결과를 단언한다. |
| NEW-4d | Required | credential rotation이 Kafka producer에 반영되지 않는다. | 완료 | Wave 1–2 P1 (fcddab7e·Wave 2 커밋): M-2f 행과 같은 수정·테스트 | - | Kafka 방식으로 해결한다. `sasl.client.callback.handler.class`에 `CredentialRuntimeRegistry`를 조회하는 handler를 넣고 JAAS에는 username만 둔다. 이러면 재인증(broker `connections.max.reauth.ms`) 때마다 새 비밀번호를 쓴다. 다른 방법은 registry의 generation 변화에 맞춰 producer를 교체하고 transport generation을 올리는 것이다. Javadoc(:17-21)은 실제 동작에 맞춘다. |
@@ -1201,3 +1201,6 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검
| P25-new-1 | 발견 | `TomcatWebSocketAbuseIT` shutdown 테스트가 부하 중 `20.0006s < 20s`로 한 번 실패, 재실행 4회 통과(타이밍 의존). | 남음 | Wave 3 P25 결과 파일 | W4 | 시간 경계 단언을 결정적 신호로 |
| P25-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0(= P24-new-2). | 남음 | Wave 3 P25 결과 파일 | W3 | P24-new-2와 함께(P28) |
| P25-new-3 | 발견 | sample `local` 프로필이 기본값과 같은 `object-storage.enabled=false`만 남김. | 남음 | Wave 3 P25 결과 파일 | W5 | 불필요한 설정 삭제 또는 이유 주석 |
| P18-new-1 | 발견 | messaging outbox의 손으로 쓴 header JSON reader가 `\\`로 끝나는 값에서 다음 header를 삼켰다. | 완료 | Wave 3 P18: PostgreSQL `jsonb_object`/`jsonb_each_text`, `OutboxPostgresIT.aHeaderValueEndingInABackslashRoundTripsWithoutSwallowingTheNextHeader` FAIL→PASS | - | - |
| P18-new-2 | 발견 | root `CLAUDE.md`가 legacy outbox/realtime seam이 `src/messaging/CLAUDE.md`에 기록돼 있다고 적음(cutover 끝남). | 완료 | Wave 3 라운드 2 통합: `CLAUDE.md` Module families 문장 수정 | - | - |
| P18-new-3 | 발견 | actuator security chain이 auto-configuration이 되어, web security를 직접 켜지 않은 조립은 Boot 기본 actuator chain을 받는다(설계 노트). | 남음 | Wave 3 P18 결과 파일, `composition/service-runtime/.../ManagementSecurityConfig.java` | W5 | service-runtime README에 켜짐 조건 명시 |
+5 -2
View File
@@ -31,8 +31,11 @@ status: stub
- relay 스케줄러는 발행 포트(`OutboxMessagePublishPort`, messaging bridge가 제공)가 있을 때만
생긴다. messaging을 고르지 않은 배포에서는 relay가 없고 PENDING row가 그대로 남는다(MSG-024의
"DEAD까지 소진"은 대역 publisher가 있던 때의 이야기다). messaging 모듈이 켜져 있는데
`APP_MESSAGING_BROKER`가 공백이면 기동이 거부된다(messaging `MessagingConfig`, messaging platform
`MessagingProviderSelection`) — broker를 설정하거나 messaging을 끈다.
`APP_MESSAGING_PRODUCER_ID`가 공백이면(messaging `MessagingConfig`) 또는 `APP_MESSAGING_BROKER`가
공백이면(messaging platform `MessagingProviderSelection`) 기동이 거부된다 — 값을 설정하거나
messaging을 끈다.
- 발행이 `REJECTED_*`로 바로 DEAD가 된다면 event의 logical destination(`app.messaging.destinations`)이
선언돼 있는지부터 본다.
- 기동은 했는데 실패가 쌓인다면 broker는 설정돼 있고 도달이 안 되는 것이다 — endpoint부터 본다.
3. `outbox.pending.size` status 분포 확인 (FAILED 누적 vs PENDING 누적)
+2 -2
View File
@@ -59,8 +59,8 @@ PostgreSQL과 직접 관련된 레지스트리 leaf는 세 개다.
| leaf | 성격 |
|---|---|
| `adapter-outbound-persistence-jpa` | 이 글의 주인공. JPA + PostgreSQL 어댑터이자 "관계형 퍼시스턴스 플랫폼" |
| `messaging-outbox-jdbc-postgresql` | vendored messaging 제품의 outbox 구현 (별개 계보) |
| `messaging-inbox-jdbc-postgresql` | 같음 |
| `messaging-reliability-jdbc-postgresql` | vendored messaging 제품의 outbox·inbox 저장소 구현 (별개 계보) |
| `messaging-reliability` | 같은 제품의 relay·consumer 로직 (stdlib) |
messaging 쪽 두 개는 **이 애플리케이션의 레이어가 아니라 vendored 라이브러리**라서 계보가
완전히 다르다. 루트 `CLAUDE.md`가 그 예외를 명시적으로 적어 두고 있고, 이 글은
-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;

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