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
+5 -3
View File
@@ -22,9 +22,11 @@ Package root: `dev.caskeleton.sample.portfolio`.
`RepoStatsAclMapper`), `adapter/identifier` (`UuidWorkLogIdFactory`).
- Contract-test fixtures the app-bootstrap verification suite analyses
(`DomainExceptionHandler`, `PortfolioErrorCode`, wire/contract tests).
- Disposable messaging contract fixture: the exact `WorkLogReservedPayload` record, its static
application-core contract contribution, sample-owned schema/digest and golden vectors. It is not
runtime-discovered, and validator compatibility remains unproven until messaging Task 6.
- The sample's integration-event contracts: `WorkLogReservedPayload` with its contribution,
schema/digest and golden vectors, and the poster contracts in `PortfolioEventContracts`. Every
outbox append goes through `PortfolioEventOutbox` → the application's encoder → the canonical
`OutboxAppendPort`. The composition registers each contract as a bean; nothing is
classpath-discovered, and payloads are not validated against their JSON Schema.
- Sample application collaborators consume invocation context through application-core ports and
must not import SLF4J/MDC.
+45 -69
View File
@@ -125,7 +125,7 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
- "WorkLog 기간이 예약됨"이라는 도메인 사실을 표현하는 이벤트입니다. **전송(transport)과
무관**합니다 — 도메인 데이터(`WorkLogId`/`WorkCategory`/`LocalDate`)만 담고 broker/wire/HTTP
타입을 일절 참조하지 않습니다. 이것을 발행 가능한 integration 이벤트로 바꾸는 일은 application
경계의 몫입니다(`application.event.WorkLogReservedIntegrationEvent` 와 그 매퍼 참고).
경계의 몫입니다(`application.event.WorkLogReservedPayload` 와 `PortfolioEventOutbox` 참고).
### 포트 — WorkLogRepository / WorkLogIdFactory / OutboxEventIdFactory
- **WorkLogRepository**: WorkLog 영속 아웃바운드 포트(구현은 adapter-persistence). `findPage` 는
@@ -134,8 +134,8 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
- **WorkLogIdFactory / OutboxEventIdFactory**: id 를 만들어 주는 도메인 포트. 둘을 **굳이 따로 둔
이유**는, 애그리거트 식별자 타입(`WorkLogId`)이 이벤트 id 모양을 묶어버리지 않게 하기 위해서입니다.
실제로는 둘 다 UUIDv7 기반이지만(identifier 어댑터가 구현), 도메인은 생성 방식을 모릅니다.
outbox 이벤트 id 는 outbox 봉투의 `eventId` 이자 `idempotencyKey` 로 쓰입니다(같은 값 → 이벤트
단위 중복 제거).
outbox 이벤트 id 는 envelope 의 `eventId` 이고, consumer 는 이 값으로 중복을 거릅니다(이벤트 단위
중복 제거).
### RepoStats
- 외부 저장소 통계를 정규화한 결과 값입니다. 아웃바운드 ACL(B7)을 통과한 뒤에만 만들어집니다.
@@ -154,17 +154,21 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
### CreateWorkLogUseCase — 생성 + outbox 동시 기록 (dual-write 금지)
- WorkLog 를 저장하면서 `WorkLogReserved` outbox 이벤트를 **같은 쓰기 트랜잭션 안에서** 함께
적재하는 예시입니다. 핵심은 `repository.save(...)` 와 `outboxAppendPort.append(...)` 가 같은
적재하는 예시입니다. 핵심은 `repository.save(...)` 와 outbox append 가 같은
`tx.inWrite { ... }` 블록 안에 있다는 점입니다. 저장이나 적재 중 하나라도 실패하면 트랜잭션
전체가 롤백됩니다 — "DB 한 번, 브로커 한 번" 식의 분리된 이중 쓰기(dual-write)를 막는 보장입니다.
- 순서: ① 저장된 애그리거트로 도메인 이벤트 생성 → ② 매퍼로 integration 이벤트로 변환(경계는
application) → ③ 직접 만든 JSON 페이로드로 직렬화 → ④ 같은 트랜잭션에서 outbox 에 append.
- `eventId` 는 `OutboxEventIdFactory`(UUIDv7) 로 만들고, `idempotencyKey = eventId` 로 둡니다
(이벤트 단위 중복 제거).
- 순서: ① 저장된 애그리거트로 도메인 이벤트 생성 → ② payload record(`WorkLogReservedPayload`)로
변환(경계는 application) → ③ `PortfolioEventOutbox` 가 draft 를 만들어 `IntegrationEventEncoderPort`
로 encode → ④ 같은 트랜잭션에서 `OutboxAppendPort` 에 append. outbox append 모델은 canonical
하나입니다(소유자 결정 7). 포스터 이벤트(`PosterEventPublisher`, `PosterImagePublicationEventPublisher`)도
같은 길로 갑니다.
- `eventId` 는 `OutboxEventIdFactory`(UUIDv7) 로 만듭니다(이벤트 단위 중복 제거 키).
- `correlationId` 는 application-core의 `CorrelationIdPort`로 읽습니다. inbound web adapter가
sanitized MDC 값을 포트 뒤에서 제공하므로 sample application 코드는 SLF4J/MDC를 알지 않습니다.
요청 밖에서 실행되거나 값이 blank면 `eventId`를 그대로 `correlationId`로 사용해 이벤트가
최소한 자신을 가리키게(self-correlation) 폴백합니다.
요청 밖에서 실행되거나 값이 blank이거나 canonical identity 문법에 맞지 않으면 `eventId`를 그대로
`correlationId`로 사용해 이벤트가 최소한 자신을 가리키게(self-correlation) 폴백합니다.
- aggregate 순서는 발생 시각(마이크로초)입니다. sample 애그리거트에는 event 카운터가 없고, 시간
순서는 옛 outbox 가 풀어 주던 순서와 같습니다. version 컬럼이 있는 서비스는 그것을 씁니다.
- 쓰기 작업이라 `@RequiresPermission("worklog:write")` 로 권한을 요구합니다(이 권한은 `user`/`admin`
역할 묶음에 부여).
@@ -207,22 +211,6 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
projection 도 저장소 기반이면 여전히 `READ_REPOSITORY` 입니다 — "projection 이냐 애그리거트냐"는
반환 *모양*의 축이고, 저장소 접근 *수준*과는 별개라서 새 capability enum 이 필요 없습니다.
### WorkLogReservedIntegrationEvent / …Mapper — integration(wire) 이벤트
- **IntegrationEvent**: 도메인 이벤트와 달리 아웃바운드 어댑터가 실제로 발행할(예: Kafka)
직렬화 가능한 경계 소유 형태입니다. 도메인 사실을 wire 계약으로 옮기는 일 — 값 객체를 원시
타입으로 평탄화, wire 표현 선택 — 은 application 의 관심사라서 application 계층에 둡니다. 도메인은
wire 를 모릅니다.
- **Mapper**: 도메인 이벤트 → integration 이벤트 변환을 **application 경계에서** 수행하고, 트랜잭션
outbox 용 JSON 페이로드 문자열로 직렬화합니다.
- JSON 직렬화(`toJson`)는 의존성을 늘리지 않으려고 RFC 8259 §7 이스케이프까지 직접 구현했습니다.
실제 프로젝트라면 스키마 직렬화 계약(Avro/Protobuf, 스키마 레지스트리 붙은 Jackson)을 써야
합니다 — 샘플은 새 의존성 0을 유지합니다. 세 필드는 도메인 식별자와 enum 이름뿐이라 PII/토큰/
원문 본문이 없습니다.
- 이벤트 타입 이름 `"worklog.reserved"`: `도메인.동사` 패턴의 안정적인 점-구분 논리명입니다.
outbox relay 규약(`topic = eventType`)에 따라 그대로 브로커 토픽 이름이 됩니다. integration
이벤트의 클래스 단순명을 쓰는 대안도 있지만, 클래스 이름을 바꾸면 토픽이 조용히 바뀌어 컨슈머가
깨질 수 있어, 안정적인 문자열 리터럴을 택했습니다(토픽 마이그레이션 계획 없이는 바꾸지 말 것).
### WorkLogReservedPayload / …ContractContribution — canonical contract fixture
- `WorkLogReservedPayload`는 새 closed contract SPI에 제공하는 exact final record다. v1은
@@ -233,12 +221,12 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
- contribution은 contract ID, exact payload type/component order, classpath resource ID, checked-in
digest와 provider-neutral descriptor만 제공한다. JSON mapper, physical topic, Kafka 설정을 소유하지
않으며 매 호출 filesystem I/O도 하지 않는다.
- 기존 3-field `WorkLogReservedIntegrationEvent`/hand-rolled mapper는 현재 legacy outbox
characterization 경로에 남아 있다. 새 1-field canonical payload는 그 타입을 조용히 대체하지 않으며,
closed catalog와 encoder가 조립되기 전까지 양쪽은 서로 호출하거나 직렬화하지 않는다.
- 현재는 classpath scanning이나 runtime discovery가 없다. Task 5의 closed catalog 조립 전에는
자동 등록되지 않고, Task 6 validator qualification 전에는 Draft 2020-12 validator compatibility를
주장하지 않는다.
- `CreateWorkLogUseCase`가 이 contract로 발행한다. 예전의 3-field `WorkLogReservedIntegrationEvent`와
손으로 짠 JSON 매퍼는 outbox 를 canonical 로 통일하면서 삭제했다(2026-09-28).
- 포스터 이벤트의 contract 는 `PortfolioEventContracts`(schema 는 `contracts/messaging/poster.*`)에
있다. 조립(`SampleApplicationUseCaseConfig`)이 contract 마다 bean 을 등록하고, 템플릿 encoder 가 그
bean 들로 닫힌 catalog 를 만든다. classpath scanning 은 없다. encoder 는 선언한 schema hash 를 schema
파일과 대조하지만 Draft 2020-12 validator 로 payload 를 검증하지는 않는다.
### RepoStatsPort
- 외부 저장소 통계를 가져오는 아웃바운드 포트(구현은 adapter-outbound).
@@ -391,13 +379,14 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
## bootstrap — 샘플 전용 구성 루트
> **이 패키지가 왜 존재하는가 (공통 배경):** 프로덕션 조립은 `app-bootstrap` 모듈이 합니다. 그런데
> **이 패키지가 왜 존재하는가 (공통 배경):** 프로덕션 조립은 `app-bootstrap` 모듈이 합니다.
> `sample-portfolio` 는 일부러 `app-bootstrap` 에 의존하지 않습니다(샘플이 부트스트랩을 끌어오면
> 안 됨). 그래서 스캔으로 자동 발견되지 않고 오직 `app-bootstrap` 에만 있는 구성 루트 빈들
> (tracing/metrics/idempotency/privacy/management/domain-context 등)을, 여기 `bootstrap.*` 패키지가
> **샘플 전용으로 동등하게 복제**해 제공합니다. 모두 일회용(disposable)입니다 — `sample-portfolio`
> 모듈을 지우면 함께 사라지고 프로덕션에는 영향이 없습니다. 프로덕션(`CaSkeletonApplication`)은 원래
> `app-bootstrap` 빈들을 그대로 씁니다.
> 안 됨). 두 구성 루트가 함께 필요한 조립은 공용 `composition:*` 모듈이 하고, 샘플은 app-bootstrap과
> 같은 `runtimeOnly` 한 줄로 받습니다 — tracing·metrics 계약 filter·domain context·user principal
> 가명화·actuator 보안 chain은 `composition:service-runtime`, 멱등성 executor는
> `composition:idempotency`. 예전에는 이것들을 여기 `bootstrap.*` 패키지에 복사해 두었고, 복사본은
> 이미 원본과 갈라져 있었습니다(런타임 어휘에 없는 `staging` 샘플 레이트, typed startup 실패 대신
> `IllegalStateException`). 여기 남은 것은 샘플만의 결정입니다.
### SamplePortfolioApplication — 독립 실행 구성 루트
- 관계형 저장소는 다른 서비스와 똑같이 고른다: `build.gradle`의
@@ -429,35 +418,22 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{
Flyway 위치는 persistence-jpa 모듈이 준다. 모듈의 `migrationStartupRunner`는
`@ConditionalOnMissingBean(FlywayMigrationStrategy)`라 이 전략이 있으면 물러난다.
### 분산 추적 복제본 — SampleTracingConfig / …Settings / …SampleRateResolver / …EnvironmentPostProcessor / SampleMicrometerSpanErrorRecorder
- `app-bootstrap` 의 tracing 구성 루트를 샘플 전용으로 옮긴 것들입니다(위 "공통 배경" 참고). tracing
런타임(OTel/Micrometer 브리지)이 샘플 build.gradle 에 켜져 있지만, 그 빈들을 등록하는 조립 코드는
`app-bootstrap` 에만 있어서 복제했습니다.
- **per-profile 기본 샘플 레이트(SampleRateResolver)**: `prod=0.01`, `staging=0.10`, `dev/local=1.0`
(그 외 프로파일도 1.0). 설정값(`APP_TRACING_SAMPLE_RATE`)이 `[0.0, 1.0]` 범위로 들어오면 그 값이
per-profile 기본을 이깁니다.
- **EnvironmentPostProcessor**: 해소된 effective 레이트를 native 키
`management.tracing.sampling.probability` 로 이어줘, 실제 OTel sampler 가 gauge 값과 일치하게 합니다.
사용자가 native 키를 직접 지정했으면 그 값을 우선합니다. (이 PostProcessor 는 샘플 자신의
`META-INF/spring.factories` 로 등록됩니다.)
- **SampleMicrometerSpanErrorRecorder**: 현재 span 에 예외를 `error.code` 태그와 함께 기록(D12).
Tracer 가 있으면 실제 recorder, 없으면 NOOP 로 동작합니다(adapter-web `GlobalExceptionHandler` 가
`ObjectProvider` 로 집어 씀).
### 공용 runtime 배선 — `composition:service-runtime`
- tracing(`TracingConfig`, 샘플 레이트 resolver, sampling bridge `EnvironmentPostProcessor`,
`MicrometerSpanErrorRecorder`), metrics 계약 filter(`MetricsContractConfig`), domain context
propagator(`DomainContextConfig`), user principal 가명화(`PseudonymizationConfig`/`PrivacySettings`),
actuator 보안 chain(`ManagementSecurityConfig`)을 app-bootstrap과 같은 모듈에서 받습니다.
설정 키(`ca-skeleton.tracing.*`, `ca-skeleton.privacy.*`)는 그대로입니다.
- 샘플 레이트 기본값은 공용 런타임 어휘(`RuntimeEnvironment`)를 따릅니다: `prod=0.01`, 그 밖은 1.0.
샘플 복사본에만 있던 `staging=0.10` 분기는 삭제했습니다 — `staging` 프로파일은 이 템플릿에 없습니다.
- **SampleManagementSecurityConfig**: 샘플의 actuator chain은 복사본이 아니라 샘플만의 결정입니다
(IdP 없이 둘러볼 수 있는 공개 데모라 모든 요청 허용). 공용 모듈의 chain과 같은 bean 이름
`actuatorSecurityFilterChain` 으로 선언해, 공용 chain이 물러나게 합니다. 그래서 `loggers` 는
읽기 전용으로 둡니다(`SampleActuatorLoggersAccessTest`).
### 그 밖의 부트스트랩 복제본
- **SampleMetricsContractConfig**: Micrometer `MeterFilter` 두 개를 meter 등록 전에 설치합니다 —
고-cardinality 태그 키를 막는 필터(D8)와 SLO 기반 히스토그램 분포 필터(D9, 소유한 timer 이름에만 적용).
- **SampleIdempotencyConfig**: 샘플은 `ca-skeleton.capabilities.idempotency.provider=postgresql`
로 `persistence-jpa` 의 PostgreSQL store 를 고릅니다. 샘플은 app-bootstrap 에 의존할 수 없으므로
(`modules.json`) `IdempotencyExecutor` 는 이 설정이 한 번 만듭니다. app-bootstrap
`IdempotencySettings` 와 같은 prefix·같은 기본값에서 executor 가 쓰는 값만 읽고, provider 가
`disabled` 면 만들지 않습니다. 예전 `SampleIdempotencySettings`(v1 `ca-skeleton.idempotency.ttl`)와
`jdbc` provider 는 삭제됐습니다.
- **SamplePseudonymizationConfig / SamplePrivacySettings**: adapter-web `RequestLoggingFilter` 가
`UserPrincipalPseudonymizerPort` 를 주입받으므로 그 포트를 채웁니다. salt 는
`APP_PRIVACY_PSEUDONYMIZATION_SALT` 에서 오며, 비어 있으면 로컬/테스트가 시작은 되도록 dev 센티넬
salt 로 폴백합니다(프로덕션 전엔 실제 시크릿 값을 넣을 것).
- **SampleDomainContextConfig**: `adapter-persistence-rdbms` 의 `DomainContextAuditContextPort` 가
`DomainContextPropagator` 빈을 무조건 주입받으므로, 기본 `THREAD_LOCAL` 전략 구현
(`ThreadLocalDomainContextPropagator`)을 제공합니다 — async 데코레이터를 안 켜는 WorkLog 데모에
적합합니다.
### 그 밖의 부트스트랩 구성
- **멱등성 executor**: 샘플은 `ca-skeleton.capabilities.idempotency.provider=postgresql`
로 `persistence-jpa` 의 PostgreSQL store 를 고르고, executor 는 app-bootstrap 과 같은
`composition:idempotency` 모듈이 만듭니다(`runtimeOnly` 한 줄). 예전의 샘플 복사본
`SampleIdempotencyConfig`(상한 검증 없이 `Binder`로 읽고 store 를 하나로 가정)는 삭제됐고,
`Clock` 과 `@EnableScheduling` 만 `bootstrap/runtime/SampleSchedulingConfig` 로 남았습니다.
+9
View File
@@ -56,6 +56,13 @@ dependencies {
// Object storage adapter provides the canonical staged-publication ports (declared in
// application-objectstorage) the poster image publication use cases run on.
runtimeOnly project(':adapter:outbound:objectstorage')
// The request-idempotency executor, built by the same module app-bootstrap uses rather than a
// sample copy. It composes over the PostgreSQL store persistence-jpa contributes.
runtimeOnly project(':composition:idempotency')
// Tracing, the metrics contract filters, domain-context propagation and user-principal
// pseudonymization: the same module app-bootstrap uses, instead of the sample copies that had
// drifted from it. The sample's public actuator chain overrides the module's by bean name.
runtimeOnly project(':composition:service-runtime')
implementation project(':adapter:inbound:web')
implementation project(':shared-contract')
implementation 'org.springframework.boot:spring-boot-starter'
@@ -101,6 +108,8 @@ dependencies {
testFixturesCompileOnly 'org.springframework.boot:spring-boot-autoconfigure'
// Real PostgreSQL adapter/migration semantics.
// SampleIdempotencyReplayIntegrationTest composes the executor module over the real store.
integrationTestImplementation project(':composition:idempotency')
integrationTestImplementation 'org.testcontainers:testcontainers-postgresql'
integrationTestImplementation 'org.testcontainers:testcontainers-junit-jupiter'
integrationTestImplementation 'org.springframework.boot:spring-boot-testcontainers'
@@ -7,10 +7,12 @@ import dev.caskeleton.application.idempotency.IdempotentAction;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.objectstorage.identity.ObjectOperationId;
import dev.caskeleton.application.transaction.OperationId;
import dev.caskeleton.composition.idempotency.IdempotencyAutoConfiguration;
import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester;
import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservation;
import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservationCodec;
import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageSanitizedIdempotencyContextFactory;
import dev.caskeleton.sample.portfolio.bootstrap.runtime.SampleSchedulingConfig;
import dev.caskeleton.sample.portfolio.domain.poster.PosterId;
import dev.caskeleton.sample.portfolio.testinfra.PostgreSqlTestContainer;
import java.nio.charset.StandardCharsets;
@@ -106,9 +108,9 @@ class SampleIdempotencyReplayIntegrationTest {
DataSourceAutoConfiguration.class,
JdbcTemplateAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
FlywayAutoConfiguration.class))
.withUserConfiguration(
Class.forName(POSTGRESQL_STORE_CONFIG), SampleIdempotencyConfig.class)
FlywayAutoConfiguration.class,
IdempotencyAutoConfiguration.class))
.withUserConfiguration(Class.forName(POSTGRESQL_STORE_CONFIG), SampleSchedulingConfig.class)
.withPropertyValues(
// The sample's shipped default.
"ca-skeleton.capabilities.idempotency.provider=postgresql",
@@ -1,49 +0,0 @@
package dev.caskeleton.sample.portfolio.application.event;
/**
* The one JSON string writer the sample's event payloads use.
*
* <p>Three publishers each carried their own copy, and one of them escaped only the reverse solidus
* and the quote — a value holding a control character would have produced a payload that is not
* JSON. The sample stays framework-free in its application layer, so this is a small RFC 8259 §7
* writer rather than a Jackson dependency.
*/
final class EventJson {
private EventJson() {}
/** A {@code "key":"value"} member with the value escaped per RFC 8259 §7. */
static String field(String key, String value) {
return "\"" + key + "\":\"" + escape(value) + "\"";
}
/** A {@code "key":number} member. */
static String number(String key, long value) {
return "\"" + key + "\":" + value;
}
/**
* Escapes a string for a JSON string literal: reverse solidus, quotation mark and the C0 control
* characters (U+0000–U+001F), the escapes RFC 8259 §7 makes mandatory. {@code null} is written as
* the empty string.
*/
static String escape(String value) {
if (value == null) {
return "";
}
StringBuilder escaped = new StringBuilder(value.length());
for (int index = 0; index < value.length(); index++) {
char c = value.charAt(index);
if (c == '\\') {
escaped.append("\\\\");
} else if (c == '"') {
escaped.append("\\\"");
} else if (c < 0x20) {
escaped.append(String.format("\\u%04x", (int) c));
} else {
escaped.append(c);
}
}
return escaped.toString();
}
}
@@ -0,0 +1,80 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.ContractDescriptor;
import dev.caskeleton.application.messaging.contract.ContractId;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
import dev.caskeleton.application.messaging.contract.LogicalDestinationId;
import dev.caskeleton.application.messaging.contract.SchemaResourceId;
import dev.caskeleton.application.messaging.contract.Sha256;
import java.lang.reflect.RecordComponent;
import java.time.Duration;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
/**
* One portfolio integration-event contract: its id and payload version, the payload record, and the
* SHA-256 of its schema file under {@code contracts/messaging/<id>/v<version>.schema.json}.
*
* <p>Every portfolio event goes to the same logical destination under the same delivery descriptor,
* so only what differs between contracts is a component here. The encoder checks the declared hash
* against the schema file at startup; editing a schema without its hash fails the boot rather than
* stamping events with a hash of a schema that no longer exists.
*
* @param contractId the version-free contract id
* @param payloadVersion the payload schema version
* @param exactPayloadRecordType the payload record this contract carries
* @param payloadSchemaHash SHA-256 of the schema file's exact bytes
* @param <P> the payload record type
*/
public record PortfolioEventContract<P extends IntegrationPayload>(
ContractId contractId,
int payloadVersion,
Class<P> exactPayloadRecordType,
Sha256 payloadSchemaHash)
implements IntegrationEventContractContribution<P> {
/** Where every portfolio event goes; a deployment binds it to a broker destination. */
public static final LogicalDestinationId DESTINATION =
new LogicalDestinationId("portfolio-domain-events");
private static final ContractDescriptor DESCRIPTOR =
new ContractDescriptor(
"sample-portfolio",
DESTINATION,
"json-envelope-v1",
true,
64 * 1024,
128 * 1024,
ContractDescriptor.SensitivityClassification.INTERNAL,
Duration.ofDays(7));
/** A contract whose schema hash is given as lower-case hex. */
static <P extends IntegrationPayload> PortfolioEventContract<P> of(
String contractId, int payloadVersion, Class<P> payloadType, String schemaSha256Hex) {
return new PortfolioEventContract<>(
new ContractId(contractId),
payloadVersion,
payloadType,
new Sha256(HexFormat.of().parseHex(schemaSha256Hex)));
}
@Override
public List<String> canonicalRecordComponentOrder() {
return Arrays.stream(exactPayloadRecordType.getRecordComponents())
.map(RecordComponent::getName)
.toList();
}
@Override
public SchemaResourceId payloadSchemaResource() {
return new SchemaResourceId(
"contracts/messaging/" + contractId.value() + "/v" + payloadVersion + ".schema.json");
}
@Override
public ContractDescriptor descriptor() {
return DESCRIPTOR;
}
}
@@ -0,0 +1,80 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import java.util.List;
/**
* Every integration event the sample publishes, one constant per contract.
*
* <p>The composition registers each as a bean, which is how the application's encoder learns the
* closed catalog. The hashes are of the schema files under {@code contracts/messaging/}; {@code
* PortfolioEventContractsTest} and the encoder at startup both hold them to those bytes.
*/
public final class PortfolioEventContracts {
public static final PortfolioEventContract<PosterCreatedPayload> POSTER_CREATED =
PortfolioEventContract.of(
"poster.created",
1,
PosterCreatedPayload.class,
"8be3a72b7b469d894d06bd30f79f565feb23fbf698674d5caee094de5a2300fb");
public static final PortfolioEventContract<PosterImageAttachedPayload> POSTER_IMAGE_ATTACHED =
PortfolioEventContract.of(
"poster.image-attached",
1,
PosterImageAttachedPayload.class,
"8021e7676928d8cb0fd29edf052be8d37fb5e87284c3eb4b947942d395aedd99");
public static final PortfolioEventContract<PosterIdPayload> POSTER_PUBLISHED =
PortfolioEventContract.of(
"poster.published",
1,
PosterIdPayload.class,
"d89954e3074fc015a20d616bf0ec1cb46c088fa417d78e006163f1c2dc61170c");
public static final PortfolioEventContract<PosterIdPayload> POSTER_ARCHIVED =
PortfolioEventContract.of(
"poster.archived",
1,
PosterIdPayload.class,
"c71019a727f351aa26afbf6c9246b6cf1a7abcfd2b6bb3ee1185dfce6be504d8");
public static final PortfolioEventContract<PosterIdPayload> POSTER_DELETED =
PortfolioEventContract.of(
"poster.deleted",
1,
PosterIdPayload.class,
"c5310821c338be5aa916d126008a0a0f4be6c6999775018ce29cbefc44c8a942");
public static final PortfolioEventContract<PosterImageAttachmentPreparedPayload>
POSTER_IMAGE_ATTACHMENT_PREPARED =
PortfolioEventContract.of(
"poster.image-attachment-prepared",
1,
PosterImageAttachmentPreparedPayload.class,
"179160ec458b710535c7846a47a1abceab1a743a3a5f11633c47c2115e82e2c4");
public static final PortfolioEventContract<PosterImageAttachmentReadyPayload>
POSTER_IMAGE_ATTACHMENT_READY =
PortfolioEventContract.of(
"poster.image-attachment-ready",
2,
PosterImageAttachmentReadyPayload.class,
"1a256fa47c382a4900ed8f852da9256a01ef1ddb2dc5b0b75047f827ae81644e");
private PortfolioEventContracts() {}
/** The closed catalog: every contract above plus {@code portfolio.worklog.reserved} v1. */
public static List<IntegrationEventContractContribution<?>> all() {
return List.of(
POSTER_CREATED,
POSTER_IMAGE_ATTACHED,
POSTER_PUBLISHED,
POSTER_ARCHIVED,
POSTER_DELETED,
POSTER_IMAGE_ATTACHMENT_PREPARED,
POSTER_IMAGE_ATTACHMENT_READY,
new WorkLogReservedContractContribution());
}
}
@@ -0,0 +1,107 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
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.IntegrationEventDraft;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory;
import java.time.Clock;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
/**
* Appends one portfolio integration event to the transactional outbox: build the draft, encode it,
* append it. MUST be called from within a use case's {@code TransactionPort.inWrite(...)} block, so
* the append joins the business write (no dual write).
*
* <p>What the draft needs and a domain event does not carry is decided here, once:
*
* <ul>
* <li>The event id is a UUIDv7 from {@link OutboxEventIdFactory}; consumers deduplicate on it.
* <li>The correlation id is the request's, through {@link CorrelationIdPort}, when it fits the
* canonical identity grammar; otherwise — off-HTTP, or a caller-supplied header that does not
* fit — the event id. An unusable header must not fail the business write.
* <li>The aggregate order is the occurrence time in microseconds. The sample's aggregates keep no
* event counter, and time order is the order the pre-canonical outbox released them in; a
* service whose aggregate has a version column should use that instead.
* </ul>
*/
public final class PortfolioEventOutbox {
/** The tenant every sample aggregate belongs to; the sample is single-tenant. */
static final String TENANT_SCOPE = "portfolio";
private static final Pattern CORRELATION_GRAMMAR =
Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,95}");
private final OutboxAppendPort outbox;
private final IntegrationEventEncoderPort encoder;
private final OutboxEventIdFactory eventIds;
private final CorrelationIdPort correlations;
private final Clock clock;
public PortfolioEventOutbox(
OutboxAppendPort outbox,
IntegrationEventEncoderPort encoder,
OutboxEventIdFactory eventIds,
CorrelationIdPort correlations,
Clock clock) {
this.outbox = Objects.requireNonNull(outbox, "outbox");
this.encoder = Objects.requireNonNull(encoder, "encoder");
this.eventIds = Objects.requireNonNull(eventIds, "eventIds");
this.correlations = Objects.requireNonNull(correlations, "correlations");
this.clock = Objects.requireNonNull(clock, "clock");
}
/**
* Appends an event of {@code contract} about one aggregate.
*
* @param contract the event's contract
* @param aggregateType the aggregate's type, e.g. {@code poster}
* @param aggregateId the aggregate's id
* @param payload the payload record
* @param <P> the payload type
*/
public <P extends IntegrationPayload> void append(
IntegrationEventContractContribution<P> contract,
String aggregateType,
String aggregateId,
P payload) {
String eventId = eventIds.newEventId();
Instant occurredAt = clock.instant();
String correlationId =
correlations
.currentCorrelationId()
.filter(value -> CORRELATION_GRAMMAR.matcher(value).matches())
.orElse(eventId);
outbox.append(
encoder.encode(
new IntegrationEventDraft<>(
new EventId(eventId),
contract.contractId(),
contract.payloadVersion(),
contract.descriptor().logicalDestination(),
new AggregateIdentity(TENANT_SCOPE, aggregateType, aggregateId),
new AggregateOrder(sequenceOf(occurredAt), 0),
occurredAt,
correlationId,
Optional.empty(),
payload)));
}
/** Microseconds since the epoch, increasing with time; at least 1, as an aggregate order is. */
static long sequenceOf(Instant occurredAt) {
return Math.max(
1L,
Math.addExact(
Math.multiplyExact(occurredAt.getEpochSecond(), 1_000_000L),
occurredAt.getNano() / 1_000L));
}
}
@@ -0,0 +1,11 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
/**
* Payload of {@code poster.created} v1.
*
* @param posterId the new poster
* @param title its title
*/
public record PosterCreatedPayload(String posterId, String title) implements IntegrationPayload {}
@@ -1,87 +1,58 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.sample.portfolio.domain.poster.PosterArchived;
import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated;
import dev.caskeleton.sample.portfolio.domain.poster.PosterDeleted;
import dev.caskeleton.sample.portfolio.domain.poster.PosterImageAttached;
import dev.caskeleton.sample.portfolio.domain.poster.PosterPublished;
import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory;
import java.time.Clock;
import java.time.Instant;
/**
* Publishes Poster lifecycle domain events to the transactional outbox. MUST be invoked from within
* a use case's {@code TransactionPort.inWrite(...)} block so the append participates in the same
* write transaction (no dual-write). Factors out the outbox plumbing shown once in {@code
* CreateWorkLogUseCase}, because Poster emits five lifecycle events. {@code eventId} (a UUIDv7 from
* {@link OutboxEventIdFactory}) doubles as the idempotency key; {@code correlationId} comes through
* {@link CorrelationIdPort}, falling back to {@code eventId} off-HTTP.
* Publishes Poster lifecycle domain events to the transactional outbox, one contract per event.
* MUST be invoked from within a use case's {@code TransactionPort.inWrite(...)} block so the append
* participates in the same write transaction (no dual-write). The identities every event needs are
* {@link PortfolioEventOutbox}'s; this class only maps a domain event to its payload.
*/
public class PosterEventPublisher {
private final LegacyOutboxAppendPort outbox;
private final OutboxEventIdFactory eventIdFactory;
private final CorrelationIdPort correlationIdPort;
private final Clock clock;
static final String AGGREGATE_TYPE = "poster";
public PosterEventPublisher(
LegacyOutboxAppendPort outbox,
OutboxEventIdFactory eventIdFactory,
CorrelationIdPort correlationIdPort,
Clock clock) {
private final PortfolioEventOutbox outbox;
public PosterEventPublisher(PortfolioEventOutbox outbox) {
this.outbox = outbox;
this.eventIdFactory = eventIdFactory;
this.correlationIdPort = correlationIdPort;
this.clock = clock;
}
public void publishCreated(PosterCreated e) {
append(
"poster.created",
e.posterId().value(),
"{"
+ EventJson.field("posterId", e.posterId().value())
+ ","
+ EventJson.field("title", e.title())
+ "}");
String posterId = e.posterId().value();
outbox.append(
PortfolioEventContracts.POSTER_CREATED,
AGGREGATE_TYPE,
posterId,
new PosterCreatedPayload(posterId, e.title()));
}
public void publishImageAttached(PosterImageAttached e) {
append(
"poster.image-attached",
e.posterId().value(),
"{"
+ EventJson.field("posterId", e.posterId().value())
+ ","
+ EventJson.field("imageKey", e.imageKey())
+ "}");
String posterId = e.posterId().value();
outbox.append(
PortfolioEventContracts.POSTER_IMAGE_ATTACHED,
AGGREGATE_TYPE,
posterId,
new PosterImageAttachedPayload(posterId, e.imageKey()));
}
public void publishPublished(PosterPublished e) {
append("poster.published", e.posterId().value(), onlyId(e.posterId().value()));
publishIdOnly(PortfolioEventContracts.POSTER_PUBLISHED, e.posterId().value());
}
public void publishArchived(PosterArchived e) {
append("poster.archived", e.posterId().value(), onlyId(e.posterId().value()));
publishIdOnly(PortfolioEventContracts.POSTER_ARCHIVED, e.posterId().value());
}
public void publishDeleted(PosterDeleted e) {
append("poster.deleted", e.posterId().value(), onlyId(e.posterId().value()));
publishIdOnly(PortfolioEventContracts.POSTER_DELETED, e.posterId().value());
}
private void append(String eventType, String aggregateId, String payload) {
String eventId = eventIdFactory.newEventId();
String correlationId =
correlationIdPort.currentCorrelationId().filter(value -> !value.isBlank()).orElse(eventId);
outbox.append(
new NewOutboxEvent(
eventId, eventType, aggregateId, payload, Instant.now(clock), correlationId, eventId));
}
private static String onlyId(String posterId) {
return "{" + EventJson.field("posterId", posterId) + "}";
private void publishIdOnly(PortfolioEventContract<PosterIdPayload> contract, String posterId) {
outbox.append(contract, AGGREGATE_TYPE, posterId, new PosterIdPayload(posterId));
}
}
@@ -0,0 +1,12 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
/**
* Payload of the poster lifecycle events that carry nothing but which poster: {@code
* poster.published}, {@code poster.archived} and {@code poster.deleted}, each v1. The contract id
* says what happened.
*
* @param posterId the poster
*/
public record PosterIdPayload(String posterId) implements IntegrationPayload {}
@@ -0,0 +1,12 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
/**
* Payload of {@code poster.image-attached} v1, the legacy direct upload's announcement.
*
* @param posterId the poster
* @param imageKey the stored object's key
*/
public record PosterImageAttachedPayload(String posterId, String imageKey)
implements IntegrationPayload {}
@@ -0,0 +1,16 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
/**
* Payload of {@code poster.image-attachment-prepared} v1: a staged upload committed PENDING. It
* carries no locator — the object is not published yet.
*
* @param posterId the poster
* @param operationId the upload operation
* @param mediaType the declared media type
* @param exactLength the exact content length in bytes
*/
public record PosterImageAttachmentPreparedPayload(
String posterId, String operationId, String mediaType, long exactLength)
implements IntegrationPayload {}
@@ -0,0 +1,18 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.messaging.contract.IntegrationPayload;
/**
* Payload of {@code poster.image-attachment-ready} v2: the published image reference. Version 2
* because {@code poster.image-attached} v1, which carried the raw object key, came first and still
* exists for the legacy upload.
*
* @param posterId the poster
* @param operationId the upload operation
* @param reference the published image reference
* @param mediaType the media type
* @param exactLength the exact content length in bytes
*/
public record PosterImageAttachmentReadyPayload(
String posterId, String operationId, String reference, String mediaType, long exactLength)
implements IntegrationPayload {}
@@ -1,67 +1,41 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory;
import java.time.Clock;
/** Transactional locator-free publication integration notifications. */
/**
* Transactional, locator-free publication notifications for the Poster image workflow. Called
* inside the use case's write transaction; see {@link PortfolioEventOutbox}.
*/
public final class PosterImagePublicationEventPublisher {
private final LegacyOutboxAppendPort outbox;
private final OutboxEventIdFactory ids;
private final CorrelationIdPort correlations;
private final Clock clock;
private final PortfolioEventOutbox outbox;
public PosterImagePublicationEventPublisher(
LegacyOutboxAppendPort outbox,
OutboxEventIdFactory ids,
CorrelationIdPort correlations,
Clock clock) {
public PosterImagePublicationEventPublisher(PortfolioEventOutbox outbox) {
this.outbox = outbox;
this.ids = ids;
this.correlations = correlations;
this.clock = clock;
}
public void publishPrepared(PosterImageAttachmentPrepared event) {
append(
"poster.image-attachment-prepared.v1",
event.posterId().value(),
"{"
+ EventJson.field("posterId", event.posterId().value())
+ ","
+ EventJson.field("operationId", event.operationId().value())
+ ","
+ EventJson.field("mediaType", event.mediaType().canonicalText())
+ ","
+ EventJson.number("exactLength", event.contentIdentity().exactLength())
+ "}");
String posterId = event.posterId().value();
outbox.append(
PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_PREPARED,
PosterEventPublisher.AGGREGATE_TYPE,
posterId,
new PosterImageAttachmentPreparedPayload(
posterId,
event.operationId().value(),
event.mediaType().canonicalText(),
event.contentIdentity().exactLength()));
}
public void publishReady(PosterImageAttachmentReadyV2 event) {
append(
"poster.image-attachment-ready.v2",
event.posterId().value(),
"{"
+ EventJson.field("posterId", event.posterId().value())
+ ","
+ EventJson.field("operationId", event.operationId().value())
+ ","
+ EventJson.field("reference", event.reference().value())
+ ","
+ EventJson.field("mediaType", event.mediaType().canonicalText())
+ ","
+ EventJson.number("exactLength", event.contentIdentity().exactLength())
+ "}");
}
private void append(String type, String aggregate, String payload) {
String id = ids.newEventId();
String correlation =
correlations.currentCorrelationId().filter(value -> !value.isBlank()).orElse(id);
String posterId = event.posterId().value();
outbox.append(
new NewOutboxEvent(id, type, aggregate, payload, clock.instant(), correlation, id));
PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_READY,
PosterEventPublisher.AGGREGATE_TYPE,
posterId,
new PosterImageAttachmentReadyPayload(
posterId,
event.operationId().value(),
event.reference().value(),
event.mediaType().canonicalText(),
event.contentIdentity().exactLength()));
}
}
@@ -1,10 +0,0 @@
package dev.caskeleton.sample.portfolio.application.event;
/**
* Integration (wire) event derived from the {@code WorkLogReserved} domain event: the
* boundary-owned, serialisable shape an outbound adapter would publish (e.g. to Kafka). It lives in
* the application layer because translating a domain fact into a wire contract is an application
* concern; the domain stays unaware of the wire. See README.
*/
public record WorkLogReservedIntegrationEvent(
String workLogId, String category, String occurredOn) {}
@@ -1,46 +0,0 @@
package dev.caskeleton.sample.portfolio.application.event;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved;
/**
* Maps the transport-free {@code WorkLogReserved} domain event to a {@link
* WorkLogReservedIntegrationEvent} at the application boundary, and serialises it to a hand-rolled
* JSON payload string for the transactional outbox. See README.
*/
public final class WorkLogReservedIntegrationEventMapper {
/** Stable logical event type name; becomes the broker topic. See README. */
public static final String EVENT_TYPE = "worklog.reserved";
private WorkLogReservedIntegrationEventMapper() {}
/**
* Maps a {@link WorkLogReserved} domain event to its integration event form, flattening value
* objects to primitive strings.
*
* @param event the domain event; must not be {@code null}
* @return the integration event record
*/
public static WorkLogReservedIntegrationEvent toIntegrationEvent(WorkLogReserved event) {
return new WorkLogReservedIntegrationEvent(
event.workLogId().value(), event.category().name(), event.periodStart().toString());
}
/**
* Serialises a {@link WorkLogReservedIntegrationEvent} to a JSON string for the outbox {@code
* payload} field (hand-rolled, no Jackson/Gson dependency). See README.
*
* @param event the integration event to serialise; must not be {@code null}
* @return a JSON object string, e.g. {@code
* {"workLogId":"0190bd6e-7c3e-7abc-8def-0123456789ab","category":"BACKEND","occurredOn":"2025-01-01"}}
*/
public static String toJson(WorkLogReservedIntegrationEvent event) {
return "{"
+ EventJson.field("workLogId", event.workLogId())
+ ","
+ EventJson.field("category", event.category())
+ ","
+ EventJson.field("occurredOn", event.occurredOn())
+ "}";
}
}
@@ -3,31 +3,25 @@ package dev.caskeleton.sample.portfolio.application.worklog;
import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.application.security.RequiresPermission;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.usecase.CommandUseCase;
import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedIntegrationEvent;
import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedIntegrationEventMapper;
import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox;
import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedContractContribution;
import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedPayload;
import dev.caskeleton.sample.portfolio.domain.worklog.Period;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogIdFactory;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogOwner;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogRepository;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved;
import java.time.Clock;
import java.time.Instant;
/**
* Creates a new {@link WorkLog} and appends a {@link WorkLogReserved} outbox event in the same
* write transaction, demonstrating the dual-write prohibition. {@code eventId} is the UUIDv7 from
* {@link OutboxEventIdFactory} and doubles as the idempotency key; {@code correlationId} comes
* through {@link CorrelationIdPort}. See README.
* Creates a new {@link WorkLog} and appends a {@link WorkLogReserved} integration event ({@code
* portfolio.worklog.reserved} v1) in the same write transaction, demonstrating the dual-write
* prohibition. The event's identities come from {@link PortfolioEventOutbox}. See README.
*/
@RequiresPermission("worklog:write")
@UseCaseCapability(
@@ -36,28 +30,22 @@ import java.time.Instant;
repositoryAccess = RepositoryAccess.WRITE_REPOSITORY)
public class CreateWorkLogUseCase implements CommandUseCase<CreateWorkLogCommand, WorkLog> {
private static final WorkLogReservedContractContribution RESERVED =
new WorkLogReservedContractContribution();
private final WorkLogRepository repository;
private final WorkLogIdFactory idFactory;
private final OutboxEventIdFactory eventIdFactory;
private final LegacyOutboxAppendPort outboxAppendPort;
private final CorrelationIdPort correlationIdPort;
private final Clock clock;
private final PortfolioEventOutbox events;
private final TransactionPort tx;
public CreateWorkLogUseCase(
WorkLogRepository repository,
WorkLogIdFactory idFactory,
OutboxEventIdFactory eventIdFactory,
LegacyOutboxAppendPort outboxAppendPort,
CorrelationIdPort correlationIdPort,
Clock clock,
PortfolioEventOutbox events,
TransactionPort tx) {
this.repository = repository;
this.idFactory = idFactory;
this.eventIdFactory = eventIdFactory;
this.outboxAppendPort = outboxAppendPort;
this.correlationIdPort = correlationIdPort;
this.clock = clock;
this.events = events;
this.tx = tx;
}
@@ -87,33 +75,14 @@ public class CreateWorkLogUseCase implements CommandUseCase<CreateWorkLogCommand
}
/**
* Builds the {@link WorkLogReserved} domain event, maps it to an integration event, serialises
* it, and appends it to the outbox — all within the caller's transaction.
* Maps the {@link WorkLogReserved} domain event to its integration payload and appends it — all
* within the caller's transaction. The v1 contract carries the work log id only; a consumer that
* needs more reads it from the owning service.
*/
private void appendReservedEvent(WorkLog saved) {
WorkLogReserved domainEvent =
new WorkLogReserved(saved.id(), saved.category(), saved.period().start());
WorkLogReservedIntegrationEvent integrationEvent =
WorkLogReservedIntegrationEventMapper.toIntegrationEvent(domainEvent);
String payload = WorkLogReservedIntegrationEventMapper.toJson(integrationEvent);
String eventId = eventIdFactory.newEventId();
Instant occurredAt = Instant.now(clock);
String correlationId =
correlationIdPort.currentCorrelationId().filter(value -> !value.isBlank()).orElse(eventId);
outboxAppendPort.append(
new NewOutboxEvent(
eventId,
WorkLogReservedIntegrationEventMapper.EVENT_TYPE,
saved.id().value(),
payload,
occurredAt,
correlationId,
eventId // idempotencyKey = eventId
));
String workLogId = domainEvent.workLogId().value();
events.append(RESERVED, "worklog", workLogId, new WorkLogReservedPayload(workLogId));
}
}
@@ -1,10 +1,20 @@
package dev.caskeleton.sample.portfolio.bootstrap.application;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventContract;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventContracts;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox;
import dev.caskeleton.sample.portfolio.application.event.PosterCreatedPayload;
import dev.caskeleton.sample.portfolio.application.event.PosterEventPublisher;
import dev.caskeleton.sample.portfolio.application.event.PosterIdPayload;
import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachedPayload;
import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachmentPreparedPayload;
import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachmentReadyPayload;
import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher;
import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedContractContribution;
import dev.caskeleton.sample.portfolio.application.port.RepoStatsPort;
import dev.caskeleton.sample.portfolio.application.port.WorkLogSummaryQueryPort;
import dev.caskeleton.sample.portfolio.application.poster.ArchivePosterUseCase;
@@ -43,22 +53,70 @@ import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class SampleApplicationUseCaseConfig {
/**
* The closed integration-event catalog, one bean per contract. The application's encoder is built
* over every contribution bean in the context, which is how it learns these.
*/
@Bean
PosterEventPublisher posterEventPublisher(
LegacyOutboxAppendPort outbox,
PortfolioEventContract<PosterCreatedPayload> posterCreatedContract() {
return PortfolioEventContracts.POSTER_CREATED;
}
@Bean
PortfolioEventContract<PosterImageAttachedPayload> posterImageAttachedContract() {
return PortfolioEventContracts.POSTER_IMAGE_ATTACHED;
}
@Bean
PortfolioEventContract<PosterIdPayload> posterPublishedContract() {
return PortfolioEventContracts.POSTER_PUBLISHED;
}
@Bean
PortfolioEventContract<PosterIdPayload> posterArchivedContract() {
return PortfolioEventContracts.POSTER_ARCHIVED;
}
@Bean
PortfolioEventContract<PosterIdPayload> posterDeletedContract() {
return PortfolioEventContracts.POSTER_DELETED;
}
@Bean
PortfolioEventContract<PosterImageAttachmentPreparedPayload>
posterImageAttachmentPreparedContract() {
return PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_PREPARED;
}
@Bean
PortfolioEventContract<PosterImageAttachmentReadyPayload> posterImageAttachmentReadyContract() {
return PortfolioEventContracts.POSTER_IMAGE_ATTACHMENT_READY;
}
@Bean
WorkLogReservedContractContribution workLogReservedContract() {
return new WorkLogReservedContractContribution();
}
@Bean
PortfolioEventOutbox portfolioEventOutbox(
OutboxAppendPort outbox,
IntegrationEventEncoderPort encoder,
OutboxEventIdFactory eventIds,
CorrelationIdPort correlations,
Clock clock) {
return new PosterEventPublisher(outbox, eventIds, correlations, clock);
return new PortfolioEventOutbox(outbox, encoder, eventIds, correlations, clock);
}
@Bean
PosterEventPublisher posterEventPublisher(PortfolioEventOutbox events) {
return new PosterEventPublisher(events);
}
@Bean
PosterImagePublicationEventPublisher posterImagePublicationEventPublisher(
LegacyOutboxAppendPort outbox,
OutboxEventIdFactory eventIds,
CorrelationIdPort correlations,
Clock clock) {
return new PosterImagePublicationEventPublisher(outbox, eventIds, correlations, clock);
PortfolioEventOutbox events) {
return new PosterImagePublicationEventPublisher(events);
}
@Bean
@@ -117,13 +175,9 @@ public class SampleApplicationUseCaseConfig {
CreateWorkLogUseCase createWorkLogUseCase(
WorkLogRepository repository,
WorkLogIdFactory workLogIds,
OutboxEventIdFactory eventIds,
LegacyOutboxAppendPort outbox,
CorrelationIdPort correlations,
Clock clock,
PortfolioEventOutbox events,
TransactionPort transactions) {
return new CreateWorkLogUseCase(
repository, workLogIds, eventIds, outbox, correlations, clock, transactions);
return new CreateWorkLogUseCase(repository, workLogIds, events, transactions);
}
@Bean
@@ -1,20 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.context;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Sample-local substitute for {@code app-bootstrap}'s {@code DomainContextConfig}: provides the
* {@link DomainContextPropagator} bean (default {@code THREAD_LOCAL} strategy) that the scanned
* {@code DomainContextAuditContextPort} requires. Disposable. See README.
*/
@Configuration
public class SampleDomainContextConfig {
@Bean
public DomainContextPropagator domainContextPropagator() {
return new ThreadLocalDomainContextPropagator();
}
}
@@ -1,47 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.idempotency;
import dev.caskeleton.application.idempotency.IdempotencyExecutor;
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
import java.time.Clock;
import java.time.Duration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* Sample-local stand-in for {@code app-bootstrap}'s {@code IdempotencyProviderSelectionConfig}. The
* sample is its own composition root and must not depend on {@code app-bootstrap}, so it builds the
* one executor itself, over the {@link IdempotencyStorePort} the persistence-jpa provider
* contributes, from the same {@code ca-skeleton.capabilities.idempotency} keys and defaults. Also
* supplies the {@code Clock} and turns on scheduling for the sample's jobs. Disposable. See README.
*/
@Configuration
@EnableScheduling
public class SampleIdempotencyConfig {
private static final String PREFIX = "ca-skeleton.capabilities.idempotency.";
@Bean
public Clock systemClock() {
return Clock.systemUTC();
}
@Bean
@ConditionalOnExpression(
"!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()"
+ ".equalsIgnoreCase('disabled')")
public IdempotencyExecutor idempotencyExecutor(
IdempotencyStorePort store, Environment environment) {
Binder binder = Binder.get(environment);
return new IdempotencyExecutor(
store,
binder.bind(PREFIX + "processing-lease", Duration.class).orElse(Duration.ofSeconds(30)),
binder.bind(PREFIX + "replay-ttl", Duration.class).orElse(Duration.ofHours(24)),
binder.bind(PREFIX + "failure-retention", Duration.class).orElse(Duration.ofHours(24)),
binder.bind(PREFIX + "response-codec-id", String.class).orElse("json-v2"),
binder.bind(PREFIX + "policy-revision", Integer.class).orElse(2));
}
}
@@ -1,25 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.logging;
import dev.caskeleton.adapter.outbound.identifier.HmacUserPrincipalPseudonymizer;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import dev.caskeleton.sample.portfolio.bootstrap.settings.SamplePrivacySettings;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code PseudonymizationConfig}: supplies the {@code
* UserPrincipalPseudonymizerPort} that adapter-web's {@code RequestLoggingFilter} injects.
* Disposable. See README.
*/
@Configuration
@EnableConfigurationProperties(SamplePrivacySettings.class)
public class SamplePseudonymizationConfig {
@Bean
@ConditionalOnMissingBean
UserPrincipalPseudonymizerPort userPrincipalPseudonymizer(SamplePrivacySettings privacySettings) {
return new HmacUserPrincipalPseudonymizer(privacySettings.saltBytes());
}
}
@@ -10,8 +10,12 @@ import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
/**
* Sample-local actuator chain. The standalone sample is intentionally public so the demo can be
* inspected without a configured IdP; production actuator posture remains in app-bootstrap.
* The sample's actuator posture, which differs from the template's on purpose: the standalone
* sample is public so the demo can be inspected without a configured IdP.
*
* <p>Not a copy of the shared chain. {@code composition:service-runtime} ships the template's chain
* as {@code actuatorSecurityFilterChain} and steps aside when a composition root declares a bean of
* that name, which this class does; production actuator posture stays in that module.
*/
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@@ -20,7 +24,7 @@ public class SampleManagementSecurityConfig {
/** Actuator security chain ordered at {@code 0} to run BEFORE the main app chain. */
@Bean
@Order(0)
public SecurityFilterChain sampleActuatorSecurityFilterChain(HttpSecurity http) throws Exception {
public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception {
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
@@ -1,89 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.metrics;
import dev.caskeleton.shared.metrics.ForbiddenMetricTags;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import java.time.Duration;
import java.util.Set;
import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code MetricsContractConfig}: installs the
* cardinality and SLO-distribution {@code MeterFilter}s onto the {@link MeterRegistry} before any
* meters register. Disposable. See README.
*
* <p>A {@link MeterRegistryCustomizer}, for the same reason the original is: a
* {@code @PostConstruct} ran after earlier beans had already registered meters, so the filters
* missed them and Micrometer said so. Changed in step with the original — fixing one composition
* root and leaving the other would have left the warning reproducible from the sample.
*/
@Configuration
public class SampleMetricsContractConfig {
/**
* Applies both filters at registry construction.
*
* @return the customizer Boot applies to every registry it creates
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public MeterRegistryCustomizer<MeterRegistry> sampleMetricsContractMeterFilters() {
return registry ->
registry
.config()
.meterFilter(new CardinalityFilter())
.meterFilter(new DistributionFilter());
}
/** Deny meters with high-cardinality tag keys. */
private static final class CardinalityFilter implements MeterFilter {
@Override
public MeterFilterReply accept(Meter.Id id) {
for (Tag tag : id.getTags()) {
if (ForbiddenMetricTags.isForbidden(tag.getKey())) {
return MeterFilterReply.DENY;
}
}
return MeterFilterReply.NEUTRAL;
}
}
/** SLO-driven histogram config for owned timer names. */
private static final class DistributionFilter implements MeterFilter {
private static final Set<String> SLO_DRIVEN_TIMERS =
Set.of(
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause");
@Override
public DistributionStatisticConfig configure(Meter.Id id, DistributionStatisticConfig config) {
if (!SLO_DRIVEN_TIMERS.contains(id.getName())) {
return config;
}
return DistributionStatisticConfig.builder()
.percentilesHistogram(true)
.percentiles(0.5, 0.9, 0.95, 0.99)
.serviceLevelObjectives(
(double) Duration.ofMillis(100).toNanos(),
(double) Duration.ofMillis(500).toNanos(),
(double) Duration.ofSeconds(1).toNanos(),
(double) Duration.ofSeconds(5).toNanos())
.minimumExpectedValue((double) Duration.ofMillis(1).toNanos())
.maximumExpectedValue((double) Duration.ofSeconds(10).toNanos())
.build()
.merge(config);
}
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.sample.portfolio.bootstrap.runtime;
import java.time.Clock;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* The sample's clock, and scheduling for its jobs (the Poster image retirement job, the idempotency
* reaper of the PostgreSQL store).
*
* <p>The idempotency executor is not built here any more. It comes from {@code
* composition:idempotency}, the module app-bootstrap uses too, so the sample no longer carries a
* copy that read the lifecycle keys without their bounds and assumed exactly one store.
*/
@Configuration
@EnableScheduling
public class SampleSchedulingConfig {
@Bean
public Clock systemClock() {
return Clock.systemUTC();
}
}
@@ -1,33 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.settings;
import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code PrivacySettings}, bound from {@code
* ca-skeleton.privacy.*}. Supplies the HMAC salt; a blank salt falls back to a dev sentinel so
* local/test runs start. Disposable. See README.
*/
@ConfigurationProperties(prefix = "ca-skeleton.privacy")
public record SamplePrivacySettings(String pseudonymizationSalt) {
private static final Logger log = LoggerFactory.getLogger(SamplePrivacySettings.class);
static final String DEV_SENTINEL_SALT = "__LOCAL_DEV_pseudonymization_salt";
public SamplePrivacySettings {
if (pseudonymizationSalt == null || pseudonymizationSalt.isBlank()) {
log.warn(
"APP_PRIVACY_PSEUDONYMIZATION_SALT is blank; using a dev sentinel salt. "
+ "Set a real secret-manager value before production.");
pseudonymizationSalt = DEV_SENTINEL_SALT;
}
}
/** The salt as UTF-8 bytes for the HMAC key. */
public byte[] saltBytes() {
return pseudonymizationSalt.getBytes(StandardCharsets.UTF_8);
}
}
@@ -1,33 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.tracing;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code MicrometerSpanErrorRecorder}: records an
* exception on the current span with an {@code error.code} tag. Disposable. See README.
*/
public final class SampleMicrometerSpanErrorRecorder implements SpanErrorRecorder {
private final Tracer tracer;
public SampleMicrometerSpanErrorRecorder(Tracer tracer) {
this.tracer = tracer;
}
@Override
public void recordException(Throwable error, String errorCode) {
if (error == null) {
return;
}
Span span = tracer.currentSpan();
if (span == null) {
return;
}
span.error(error);
if (errorCode != null) {
span.tag("error.code", errorCode);
}
}
}
@@ -1,83 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.tracing;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.tracing.Tracer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code TracingConfig}: registers the {@link
* SpanErrorRecorder} bean and the sampling-rate gauge. Disposable. See README.
*/
@Configuration
@EnableConfigurationProperties(SampleTracingSettings.class)
public class SampleTracingConfig {
private static final Logger log = LoggerFactory.getLogger(SampleTracingConfig.class);
private final SampleTracingSettings properties;
private final Environment environment;
private final ObjectProvider<MeterRegistry> meterRegistryProvider;
public SampleTracingConfig(
SampleTracingSettings properties,
Environment environment,
ObjectProvider<MeterRegistry> meterRegistryProvider) {
this.properties = properties;
this.environment = environment;
this.meterRegistryProvider = meterRegistryProvider;
}
/** Registers the {@code tracing.sampling.rate} gauge on startup. */
@Bean
public SampleTracingSamplingRateGaugeRegistrar sampleTracingSamplingRateGaugeRegistrar() {
String activeProfile = resolveActiveProfile();
double effectiveRate =
new SampleTracingSampleRateResolver().resolve(activeProfile, properties.sampleRate());
registerGauge(activeProfile, effectiveRate);
return new SampleTracingSamplingRateGaugeRegistrar(activeProfile, effectiveRate);
}
/** Real {@link SpanErrorRecorder} bean when a Tracer is present; NOOP otherwise. */
@Bean
@ConditionalOnMissingBean(SpanErrorRecorder.class)
SpanErrorRecorder sampleSpanErrorRecorder(ObjectProvider<Tracer> tracerProvider) {
Tracer tracer = tracerProvider.getIfAvailable();
if (tracer == null) {
return SpanErrorRecorder.NOOP;
}
return new SampleMicrometerSpanErrorRecorder(tracer);
}
private String resolveActiveProfile() {
String[] profiles = environment.getActiveProfiles();
return (profiles != null && profiles.length > 0) ? profiles[0] : "local";
}
private void registerGauge(String activeProfile, double effectiveRate) {
MeterRegistry registry = meterRegistryProvider.getIfAvailable();
if (registry == null) {
return;
}
try {
Gauge.builder("tracing.sampling.rate", () -> effectiveRate)
.tag("profile", activeProfile != null ? activeProfile : "unknown")
.description("Effective distributed-tracing sample rate for the active profile")
.register(registry);
} catch (RuntimeException ex) {
log.warn("sample tracing: failed to register gauge tracing.sampling.rate", ex);
}
}
/** Value holder exposing the active profile and resolved rate for test inspection. */
public record SampleTracingSamplingRateGaugeRegistrar(
String activeProfile, double effectiveSampleRate) {}
}
@@ -1,51 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.tracing;
import java.util.Locale;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code TracingSampleRateResolver}: applies the
* per-profile default sample rate (prod=0.01, staging=0.10, dev/local=1.0). Disposable. See README.
*/
final class SampleTracingSampleRateResolver {
/**
* Returns the per-profile default sample rate (D6 SSOT).
*
* @param profile Spring active profile name; {@code null}/blank treated as "anything else"
* @return effective default rate for the profile
*/
static double defaultRateForProfile(String profile) {
if (profile == null) {
return 1.0;
}
return switch (profile.trim().toLowerCase(Locale.ROOT)) {
case "prod" -> 0.01;
case "staging" -> 0.10;
case "dev" -> 1.0;
case "local" -> 1.0;
default -> 1.0;
};
}
/**
* Resolves the effective sample rate, letting a configured override win over the per-profile
* default.
*
* @param profile active Spring profile
* @param configuredRate raw string from {@code APP_TRACING_SAMPLE_RATE}; may be blank
* @return effective sample rate in [0.0, 1.0]
*/
double resolve(String profile, String configuredRate) {
if (configuredRate != null && !configuredRate.isBlank()) {
try {
double v = Double.parseDouble(configuredRate.trim());
if (v >= 0.0 && v <= 1.0) {
return v;
}
} catch (NumberFormatException ignored) {
// fall through to profile default
}
}
return defaultRateForProfile(profile);
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.tracing;
import java.util.Map;
import org.springframework.boot.EnvironmentPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code TracingSamplingEnvironmentPostProcessor}:
* bridges the resolved sample rate to {@code management.tracing.sampling.probability} so the OTel
* sampler matches the gauge. Disposable. See README.
*/
public class SampleTracingSamplingEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final String NATIVE_KEY = "management.tracing.sampling.probability";
private static final String CA_SAMPLE_RATE_KEY = "ca-skeleton.tracing.sample-rate";
private final SampleTracingSampleRateResolver resolver = new SampleTracingSampleRateResolver();
@Override
public void postProcessEnvironment(
ConfigurableEnvironment environment, SpringApplication application) {
// User-explicit setting takes priority.
if (environment.containsProperty(NATIVE_KEY)) {
return;
}
String[] profiles = environment.getActiveProfiles();
String profile = (profiles != null && profiles.length > 0) ? profiles[0] : "local";
String configured = environment.getProperty(CA_SAMPLE_RATE_KEY);
double rate = resolver.resolve(profile, configured);
environment
.getPropertySources()
.addLast(
new MapPropertySource(
"sampleTracingSamplingBridge", Map.of(NATIVE_KEY, String.valueOf(rate))));
}
}
@@ -1,76 +0,0 @@
package dev.caskeleton.sample.portfolio.bootstrap.tracing;
import java.net.URI;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
/**
* Sample-local copy of {@code app-bootstrap}'s {@code TracingSettings}, bound from {@code
* ca-skeleton.tracing.*}. Blank sampleRate = per-profile default; non-blank must be a float in
* [0.0, 1.0]; blank otlpEndpoint = exporter off, non-blank must be a valid URL. Disposable. See
* README.
*/
@ConfigurationProperties(prefix = "ca-skeleton.tracing")
@Validated
public record SampleTracingSettings(boolean enabled, String sampleRate, Exporter exporter) {
/** Nested properties for the exporter seam. */
public record Exporter(String otlpEndpoint) {
public Exporter {
if (otlpEndpoint == null) {
otlpEndpoint = "";
}
}
/** {@code true} when an exporter endpoint is configured (non-blank). */
public boolean isConfigured() {
return otlpEndpoint != null && !otlpEndpoint.isBlank();
}
}
/** Compact canonical constructor — validation: float_between_0_and_1 + url_or_empty. */
public SampleTracingSettings {
if (sampleRate == null) {
sampleRate = "";
}
if (exporter == null) {
exporter = new Exporter("");
}
// blank = "per-profile default" signal
if (!sampleRate.isBlank()) {
validateSampleRate(sampleRate);
}
validateOtlpEndpoint(exporter.otlpEndpoint());
}
private static void validateSampleRate(String raw) {
try {
double v = Double.parseDouble(raw.trim());
if (v < 0.0 || v > 1.0) {
throw new IllegalStateException(
"APP_TRACING_SAMPLE_RATE must be a float in [0.0, 1.0]; got: " + raw);
}
} catch (NumberFormatException ex) {
throw new IllegalStateException(
"APP_TRACING_SAMPLE_RATE must be a float in [0.0, 1.0]; got: " + raw, ex);
}
}
private static void validateOtlpEndpoint(String endpoint) {
if (endpoint == null || endpoint.isBlank()) {
return;
}
try {
URI uri = URI.create(endpoint.trim());
String scheme = uri.getScheme();
if (scheme == null || scheme.isBlank()) {
throw new IllegalStateException(
"OTEL_EXPORTER_OTLP_ENDPOINT must be a valid URL with a scheme; got: " + endpoint);
}
} catch (IllegalArgumentException ex) {
throw new IllegalStateException(
"OTEL_EXPORTER_OTLP_ENDPOINT must be a valid URL or empty; got: " + endpoint, ex);
}
}
}
@@ -1,2 +0,0 @@
org.springframework.boot.EnvironmentPostProcessor=\
dev.caskeleton.sample.portfolio.bootstrap.tracing.SampleTracingSamplingEnvironmentPostProcessor
@@ -173,8 +173,8 @@ ca-skeleton:
generation-recheck-interval: ${APP_CACHE_REDIS_L1_GENERATION_RECHECK_INTERVAL:5s}
invalidation-queue-capacity: ${APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY:1024}
# The only IdempotencyStorePort this composition can produce is persistence-jpa's PostgreSQL
# store, which applies its own migration stream when selected. SampleIdempotencyConfig builds
# the executor over it; `disabled` builds neither.
# store, which applies its own migration stream when selected. composition:idempotency builds
# the executor over it (the same module app-bootstrap uses); `disabled` builds neither.
idempotency:
provider: ${APP_IDEMPOTENCY_PROVIDER:postgresql}
bootstrap:
@@ -279,8 +279,6 @@ app:
invalidation-queue-capacity: ${APP_CACHE_REDIS_L1_INVALIDATION_QUEUE_CAPACITY:1024}
messaging:
broker: ${APP_MESSAGING_BROKER:}
kafka:
brokers: ${APP_MESSAGING_KAFKA_BROKERS:}
notification:
slack-webhook:
enabled: ${APP_NOTIFICATION_SLACK_WEBHOOK_ENABLED:false}
@@ -0,0 +1,18 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:poster.archived:v1",
"title": "PosterArchived payload v1",
"type": "object",
"required": [
"posterId"
],
"properties": {
"posterId": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1,23 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:poster.created:v1",
"title": "PosterCreated payload v1",
"type": "object",
"required": [
"posterId",
"title"
],
"properties": {
"posterId": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"title": {
"type": "string",
"minLength": 1
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1,18 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:poster.deleted:v1",
"title": "PosterDeleted payload v1",
"type": "object",
"required": [
"posterId"
],
"properties": {
"posterId": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1,23 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:poster.image-attached:v1",
"title": "PosterImageAttached payload v1",
"type": "object",
"required": [
"posterId",
"imageKey"
],
"properties": {
"posterId": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"imageKey": {
"type": "string",
"minLength": 1
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1,33 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:poster.image-attachment-prepared:v1",
"title": "PosterImageAttachmentPrepared payload v1",
"type": "object",
"required": [
"posterId",
"operationId",
"mediaType",
"exactLength"
],
"properties": {
"posterId": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"operationId": {
"type": "string",
"minLength": 1
},
"mediaType": {
"type": "string",
"minLength": 1
},
"exactLength": {
"type": "integer",
"minimum": 0
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1,38 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:poster.image-attachment-ready:v2",
"title": "PosterImageAttachmentReady payload v2",
"type": "object",
"required": [
"posterId",
"operationId",
"reference",
"mediaType",
"exactLength"
],
"properties": {
"posterId": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
},
"operationId": {
"type": "string",
"minLength": 1
},
"reference": {
"type": "string",
"minLength": 1
},
"mediaType": {
"type": "string",
"minLength": 1
},
"exactLength": {
"type": "integer",
"minimum": 0
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1,18 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:dev-caskeleton:contracts:messaging:poster.published:v1",
"title": "PosterPublished payload v1",
"type": "object",
"required": [
"posterId"
],
"properties": {
"posterId": {
"type": "string",
"minLength": 1,
"maxLength": 160,
"pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]*$"
}
},
"unevaluatedProperties": false
}
@@ -0,0 +1,44 @@
package dev.caskeleton.sample.portfolio.application.event;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.messaging.contract.IntegrationEventContractContribution;
import dev.caskeleton.application.messaging.contract.Sha256;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class PortfolioEventContractsTest {
static Stream<IntegrationEventContractContribution<?>> contracts() {
return PortfolioEventContracts.all().stream();
}
/**
* The encoder refuses the same mismatch at startup; this says which contract, before anything
* boots.
*/
@ParameterizedTest
@MethodSource("contracts")
void everyContractDeclaresTheHashOfTheSchemaItShips(
IntegrationEventContractContribution<?> contract) {
// when
Sha256 shipped = sha256Of(contract.payloadSchemaResource().value());
// then
assertThat(contract.payloadSchemaHash()).isEqualTo(shipped);
}
private static Sha256 sha256Of(String resource) {
try (InputStream in =
PortfolioEventContractsTest.class.getClassLoader().getResourceAsStream(resource)) {
assertThat(in).as(resource).isNotNull();
return Sha256.of(in.readAllBytes());
} catch (IOException unreadable) {
throw new UncheckedIOException(unreadable);
}
}
}
@@ -0,0 +1,85 @@
package dev.caskeleton.sample.portfolio.application.event;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.messaging.event.AggregateIdentity;
import dev.caskeleton.application.messaging.event.AggregateOrder;
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
class PortfolioEventOutboxTest {
private static final String EVENT_ID = "0190bd6e-7c3e-7abc-8def-0123456789ff";
private static final Instant NOW = Instant.parse("2025-06-01T10:00:00.123456Z");
private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder();
@Test
void usesTheCurrentCorrelationIdWhenItFitsTheCanonicalGrammar() {
// when
append(() -> Optional.of("corr-123"));
// then
assertThat(encoder.drafts())
.singleElement()
.extracting(IntegrationEventDraft::correlationId)
.isEqualTo("corr-123");
}
/**
* A correlation id the canonical grammar refuses — a header with a space in it, say — must not
* fail the business write the event announces. Before, the pre-canonical outbox accepted any
* non-blank value; the canonical draft would throw.
*/
@ParameterizedTest
@NullSource
@ValueSource(strings = {"", " ", "not canonical", "-leading-dash"})
void fallsBackToTheEventIdWhenTheCorrelationIdIsAbsentBlankOrNotCanonical(String correlationId) {
// when
append(() -> Optional.ofNullable(correlationId));
// then
assertThat(encoder.drafts())
.singleElement()
.extracting(IntegrationEventDraft::correlationId)
.isEqualTo(EVENT_ID);
}
@Test
void theEventBelongsToThePortfolioTenantAndIsOrderedByItsOccurrenceMicrosecond() {
// when
append(Optional::empty);
// then
assertThat(encoder.drafts())
.singleElement()
.extracting(IntegrationEventDraft::aggregate, IntegrationEventDraft::order)
.containsExactly(
new AggregateIdentity("portfolio", "poster", "poster-1"),
new AggregateOrder(1_748_772_000_123_456L, 0));
}
private void append(CorrelationIdPort correlations) {
new PortfolioEventOutbox(
new InMemoryOutboxStore(),
encoder,
() -> EVENT_ID,
correlations,
Clock.fixed(NOW, ZoneOffset.UTC))
.append(
PortfolioEventContracts.POSTER_PUBLISHED,
"poster",
"poster-1",
new PosterIdPayload("poster-1"));
}
}
@@ -2,20 +2,17 @@ package dev.caskeleton.sample.portfolio.application.event;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.outbox.testkit.InMemoryOutboxStore;
import dev.caskeleton.sample.portfolio.domain.poster.PosterCreated;
import dev.caskeleton.sample.portfolio.domain.poster.PosterDeleted;
import dev.caskeleton.sample.portfolio.domain.poster.PosterId;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.NullSource;
import org.junit.jupiter.params.provider.ValueSource;
class PosterEventPublisherTest {
@@ -24,37 +21,50 @@ class PosterEventPublisherTest {
private static final Clock CLOCK =
Clock.fixed(Instant.parse("2025-06-01T10:00:00Z"), ZoneOffset.UTC);
// LegacyOutboxAppendPort is owned by application-core; a recording method reference is enough.
private final List<NewOutboxEvent> appended = new ArrayList<>();
private final InMemoryOutboxStore outbox = new InMemoryOutboxStore();
private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder();
private final PosterEventPublisher publisher =
new PosterEventPublisher(
new PortfolioEventOutbox(outbox, encoder, () -> EVENT_ID, Optional::empty, CLOCK));
@Test
void usesTheCurrentCorrelationIdWhenOneIsPresent() {
void aCreatedPosterIsAnnouncedAsPosterCreatedAboutThatPoster() {
// when
publishCreated(() -> Optional.of("corr-123"));
publisher.publishCreated(new PosterCreated(POSTER_ID, "title"));
// then
assertThat(appended)
assertThat(encoder.drafts())
.singleElement()
.extracting(NewOutboxEvent::correlationId)
.isEqualTo("corr-123");
.extracting(
draft -> draft.contractId().value(),
draft -> draft.aggregate().aggregateId(),
IntegrationEventDraft::featurePayload)
.containsExactly(
"poster.created",
POSTER_ID.value(),
new PosterCreatedPayload(POSTER_ID.value(), "title"));
}
@ParameterizedTest
@NullSource
@ValueSource(strings = {"", " "})
void fallsBackToTheEventIdWhenTheCorrelationIdIsAbsentOrBlank(String correlationId) {
@Test
void aDeletedPosterIsAnnouncedWithItsIdOnly() {
// when
publishCreated(() -> Optional.ofNullable(correlationId));
publisher.publishDeleted(new PosterDeleted(POSTER_ID));
// then
assertThat(appended)
assertThat(encoder.drafts())
.singleElement()
.extracting(NewOutboxEvent::correlationId)
.isEqualTo(EVENT_ID);
.extracting(draft -> draft.contractId().value(), IntegrationEventDraft::featurePayload)
.containsExactly("poster.deleted", new PosterIdPayload(POSTER_ID.value()));
}
private void publishCreated(CorrelationIdPort correlationIdPort) {
new PosterEventPublisher(appended::add, () -> EVENT_ID, correlationIdPort, CLOCK)
.publishCreated(new PosterCreated(POSTER_ID, "title"));
@Test
void theEncodedEventIsAppendedToTheOutbox() {
// when
publisher.publishCreated(new PosterCreated(POSTER_ID, "title"));
// then
assertThat(outbox.appended())
.extracting(event -> event.eventId().value())
.containsExactly(EVENT_ID);
}
}
@@ -2,7 +2,8 @@ package dev.caskeleton.sample.portfolio.application.event;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.outbox.testkit.OutboxEvents;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
@@ -15,9 +16,9 @@ import org.junit.jupiter.api.Test;
* Contract test (spec D7) — at-least-once delivery consumer dedupe obligation.
*
* <p>This test demonstrates the <em>executable contract</em> that any consumer of {@code
* worklog.reserved} events MUST honour: given identical {@code idempotencyKey} envelopes delivered
* multiple times (at-least-once delivery is the structural guarantee of the polling outbox),
* exactly one processing side-effect must occur.
* portfolio.worklog.reserved} events MUST honour: given the same event delivered multiple times
* (at-least-once delivery is the structural guarantee of the polling outbox), exactly one
* processing side-effect must occur.
*
* <h2>Scope</h2>
*
@@ -25,15 +26,12 @@ import org.junit.jupiter.api.Test;
* <li>The <em>dedupe mechanism</em> (in-memory {@link Set} below) is intentionally minimal — a
* real consumer uses a persistent store with TTL. Storage and TTL policy is owned by the
* consumer implementation branch (out of scope here).
* <li>This test exercises the <em>shape of the contract</em>: same {@code idempotencyKey} → skip,
* different key → process. It does not test distributed consistency or TTL expiry.
* <li>This test exercises the <em>shape of the contract</em>: same event id → skip, different id
* → process. It does not test distributed consistency or TTL expiry.
* </ul>
*
* <h2>Relationship to I12</h2>
*
* <p>{@code idempotencyKey = eventId} by default (I12 — per-event deduplication). A consumer that
* keys dedupe on the envelope's {@code idempotencyKey} therefore deduplicates at the event level,
* not the use-case call level.
* <p>The event id is the deduplication key: the outbox stores and republishes the exact validated
* envelope, so a redelivery carries the id of the first delivery.
*/
class WorkLogReservedConsumerDedupeContractTest {
@@ -44,21 +42,21 @@ class WorkLogReservedConsumerDedupeContractTest {
private final FakeWorkLogReservedConsumer consumer = new FakeWorkLogReservedConsumer();
@Test
void sameIdempotencyKeyDeliveredFiveTimesProducesExactlyOneEffect() {
void sameEventDeliveredFiveTimesProducesExactlyOneEffect() {
// given
NewOutboxEvent envelope = sampleEnvelope(KEY_A);
ValidatedIntegrationEvent envelope = sampleEnvelope(KEY_A);
// when
Collections.nCopies(5, envelope).forEach(consumer::consume);
// then
assertThat(consumer.processedEventIds)
.as("same idempotencyKey delivered 5 times must produce exactly 1 processing effect (D7)")
.as("the same event delivered 5 times must produce exactly 1 processing effect (D7)")
.containsExactly(KEY_A);
}
@Test
void distinctIdempotencyKeysAreEachProcessedOnce() {
void distinctEventsAreEachProcessedOnce() {
// when
deliver(KEY_A, KEY_B, KEY_C);
@@ -67,7 +65,7 @@ class WorkLogReservedConsumerDedupeContractTest {
}
@Test
void mixedDeliveryOnlyDeduplicatesTheRepeatedKey() {
void mixedDeliveryOnlyDeduplicatesTheRepeatedEvent() {
// when
deliver(KEY_A, KEY_A, KEY_B);
@@ -75,36 +73,19 @@ class WorkLogReservedConsumerDedupeContractTest {
assertThat(consumer.processedEventIds).containsExactly(KEY_A, KEY_B);
}
@Test
void envelopeIdempotencyKeyEqualsEventIdPerI12() {
// when
NewOutboxEvent envelope = sampleEnvelope(KEY_A);
// then
assertThat(envelope.idempotencyKey()).isEqualTo(envelope.eventId());
}
private void deliver(String... idempotencyKeys) {
for (String key : idempotencyKeys) {
consumer.consume(sampleEnvelope(key));
private void deliver(String... eventIds) {
for (String eventId : eventIds) {
consumer.consume(sampleEnvelope(eventId));
}
}
private static NewOutboxEvent sampleEnvelope(String id) {
return new NewOutboxEvent(
id,
WorkLogReservedIntegrationEventMapper.EVENT_TYPE,
"0190bd6e-7c3e-7abc-8def-0123456789ab", // aggregateId
"{\"workLogId\":\"" + id + "\",\"category\":\"BACKEND\",\"occurredOn\":\"2025-01-01\"}",
Instant.parse("2025-01-01T00:00:00Z"),
id, // correlationId
id // idempotencyKey = eventId (I12)
);
private static ValidatedIntegrationEvent sampleEnvelope(String eventId) {
return OutboxEvents.event(eventId, Instant.parse("2025-01-01T00:00:00Z"));
}
/**
* Minimal consumer with in-memory idempotencyKey tracking — the subject of this contract, not a
* port double.
* Minimal consumer with in-memory event-id tracking — the subject of this contract, not a port
* double.
*
* <p>Real implementations replace the {@link HashSet} with a persistent store (Redis / DB {@code
* idempotency_record}) and a configurable TTL. The dedupe logic shape ({@code if (seen.add(key))
@@ -115,13 +96,11 @@ class WorkLogReservedConsumerDedupeContractTest {
private final Set<String> processedKeys = new HashSet<>();
private final List<String> processedEventIds = new ArrayList<>();
/**
* Processes the envelope. If {@code idempotencyKey} was already seen, the message is silently
* skipped (at-least-once → exactly-once effect).
*/
void consume(NewOutboxEvent envelope) {
if (processedKeys.add(envelope.idempotencyKey())) {
processedEventIds.add(envelope.eventId());
/** Processes the envelope unless its event id was already seen. */
void consume(ValidatedIntegrationEvent envelope) {
String eventId = envelope.eventId().value();
if (processedKeys.add(eventId)) {
processedEventIds.add(eventId);
}
}
}
@@ -1,84 +0,0 @@
package dev.caskeleton.sample.portfolio.application.event;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.params.provider.Arguments.argumentSet;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
/**
* Verifies the JSON serialisation produced by {@link WorkLogReservedIntegrationEventMapper#toJson}
* (feature-domain-event-outbox-contract D11 + D12).
*
* <p>Hand-rolled serialisation: no Jackson dependency in main code. Checks field presence,
* ordering, and RFC 8259 §7 escape correctness.
*/
class WorkLogReservedIntegrationEventMapperJsonTest {
private static final WorkLogReservedIntegrationEvent SAMPLE_EVENT =
WorkLogReservedIntegrationEventMapper.toIntegrationEvent(
new WorkLogReserved(
WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"),
WorkCategory.BACKEND,
LocalDate.of(2025, 1, 1)));
@Test
void toJsonWritesWorkLogIdCategoryAndOccurredOnInThatOrder() {
assertThat(WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT))
.isEqualTo(
"{\"workLogId\":\"0190bd6e-7c3e-7abc-8def-0123456789ab\","
+ "\"category\":\"BACKEND\","
+ "\"occurredOn\":\"2025-01-01\"}");
}
@Test
void toJsonIsAParseableObjectWithExactlyTheThreeFields() throws IOException {
// when
String json = WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT);
// then
assertThat(json).startsWith("{").endsWith("}");
assertThat(new ObjectMapper().readTree(json).properties())
.extracting(Map.Entry::getKey)
.containsExactly("workLogId", "category", "occurredOn");
}
@ParameterizedTest
@MethodSource("escapeCases")
void escapeProducesRfc8259EscapedText(String input, String expected) {
assertThat(EventJson.escape(input)).isEqualTo(expected);
}
static Stream<Arguments> escapeCases() {
return Stream.of(
argumentSet("backslash and double quote", "path\\to\"value", "path\\\\to\\\"value"),
// Tab (0x09) and newline (0x0A) are below 0x20, so they become \\u escapes.
argumentSet("control characters", "a\tb\nc", "a\\u0009b\\u000ac"),
argumentSet("null becomes the empty string", null, ""));
}
@Test
void eventTypeConstantIsStable() {
// I9: eventType becomes the broker topic — must not change silently
assertThat(WorkLogReservedIntegrationEventMapper.EVENT_TYPE).isEqualTo("worklog.reserved");
}
@Test
void toJsonContainsNoPiiFieldNames() {
// EventPayloadPiiContractTest (Task E) also enforces this statically;
// this test makes it explicit for the sample payload shape.
assertThat(WorkLogReservedIntegrationEventMapper.toJson(SAMPLE_EVENT).toLowerCase(Locale.ROOT))
.doesNotContain("email", "password", "token", "secret");
}
}
@@ -1,36 +0,0 @@
package dev.caskeleton.sample.portfolio.application.event;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogReserved;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
/**
* Verifies the Claims-To-Verify flow: a transport-free domain event is convertible to an
* integration event at the application boundary (feature-domain-modeling-guardrails D4/D8).
*/
class WorkLogReservedIntegrationEventMapperTest {
@Test
void mapsDomainEventToIntegrationEventFlatteningValueObjects() {
// given
WorkLogReserved domainEvent =
new WorkLogReserved(
WorkLogId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"),
WorkCategory.BACKEND,
LocalDate.of(2025, 1, 1));
// when
WorkLogReservedIntegrationEvent integrationEvent =
WorkLogReservedIntegrationEventMapper.toIntegrationEvent(domainEvent);
// then
assertThat(integrationEvent)
.isEqualTo(
new WorkLogReservedIntegrationEvent(
"0190bd6e-7c3e-7abc-8def-0123456789ab", "BACKEND", "2025-01-01"));
}
}
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.objectstorage.content.CancellationView;
import dev.caskeleton.application.objectstorage.content.ObjectContentProducer;
import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId;
@@ -37,6 +38,7 @@ import dev.caskeleton.application.outbound.CallBudget;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.sample.portfolio.application.command.AbortPosterImageUploadCommand;
import dev.caskeleton.sample.portfolio.application.command.ReconcilePosterImageUploadCommand;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox;
import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher;
import dev.caskeleton.sample.portfolio.application.exception.PosterImageAlreadyPublishedException;
import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageAttachmentCompareAndSetPort;
@@ -212,7 +214,12 @@ class PosterImageAbortReconcileRaceTest {
new PosterImageOperationIdFactory.AllocatedOperation(
UUID.randomUUID(), ObjectOperationId.of(UUID.randomUUID().toString())),
new PosterImagePublicationEventPublisher(
event -> {}, () -> "0190bd6e-7c3e-7abc-8def-0123456789ff", Optional::empty, CLOCK),
new PortfolioEventOutbox(
event -> {},
new FakeIntegrationEventEncoder(),
() -> "0190bd6e-7c3e-7abc-8def-0123456789ff",
Optional::empty,
CLOCK)),
transactions,
publications,
handoffs,
@@ -7,6 +7,7 @@ import static org.mockito.Mockito.when;
import dev.caskeleton.application.idempotency.IdempotencyExecutor;
import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.objectstorage.content.CancellationView;
import dev.caskeleton.application.objectstorage.content.ObjectContentProducer;
import dev.caskeleton.application.objectstorage.content.ObjectContentProductionContext;
@@ -33,6 +34,7 @@ import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary;
import dev.caskeleton.sample.portfolio.adapter.outbound.identifier.HmacPosterImageIdempotencyScopeDigester;
import dev.caskeleton.sample.portfolio.application.command.PublishPosterImageCommand;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox;
import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher;
import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigest;
import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageOperationIdFactory;
@@ -148,7 +150,7 @@ class PosterImagePublicationWorkflowTest {
// then
assertThat(appendedInsideTransaction)
.containsExactly(Map.entry("poster.image-attachment-prepared.v1", true));
.containsExactly(Map.entry("poster.image-attachment-prepared", true));
}
@Test
@@ -225,11 +227,14 @@ class PosterImagePublicationWorkflowTest {
publications,
handoffs,
new PosterImagePublicationEventPublisher(
event ->
appendedInsideTransaction.add(Map.entry(event.eventType(), transactions.active())),
() -> "0190bd6e-7c3e-7abc-8def-0123456789ff",
Optional::empty,
CLOCK),
new PortfolioEventOutbox(
event ->
appendedInsideTransaction.add(
Map.entry(event.contractId().value(), transactions.active())),
new FakeIntegrationEventEncoder(),
() -> "0190bd6e-7c3e-7abc-8def-0123456789ff",
Optional::empty,
CLOCK)),
new PosterImagePublicationPolicy(1024),
new PosterImagePublicationParameters(
ObjectDestinationId.of("poster"),
@@ -1,15 +1,16 @@
package dev.caskeleton.sample.portfolio.application.worklog;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.application.messaging.event.IntegrationEventDraft;
import dev.caskeleton.application.messaging.event.ValidatedIntegrationEvent;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary;
import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedIntegrationEventMapper;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox;
import dev.caskeleton.sample.portfolio.application.event.WorkLogReservedPayload;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkCategory;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog;
import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId;
@@ -24,8 +25,8 @@ import java.util.Optional;
import org.junit.jupiter.api.Test;
/**
* {@link CreateWorkLogUseCase} appends a {@code WorkLogReserved} outbox event in the same {@code
* tx.inWrite} as the aggregate save (feature-domain-event-outbox-contract D2).
* {@link CreateWorkLogUseCase} appends a {@code portfolio.worklog.reserved} integration event in
* the same {@code tx.inWrite} as the aggregate save (feature-domain-event-outbox-contract D2).
*/
class CreateWorkLogOutboxTest {
@@ -34,126 +35,75 @@ class CreateWorkLogOutboxTest {
private static final Instant NOW = Instant.parse("2025-06-01T10:00:00Z");
private final DirectTransactionPort tx = new DirectTransactionPort();
private final List<NewOutboxEvent> appended = new ArrayList<>();
private final FakeIntegrationEventEncoder encoder = new FakeIntegrationEventEncoder();
private final List<ValidatedIntegrationEvent> appended = new ArrayList<>();
private final List<Boolean> appendedInsideTransaction = new ArrayList<>();
/** application-core's in-memory outbox does not expose appended events, so record them here. */
private final LegacyOutboxAppendPort outbox =
private final OutboxAppendPort outbox =
event -> {
appended.add(event);
appendedInsideTransaction.add(tx.active());
};
@Test
void appendsOneEventOfTheWorkLogReservedType() {
void appendsOneWorkLogReservedEventAboutTheCreatedWorkLog() {
// when
createWith(Optional::empty);
WorkLog created = create();
// then
assertThat(appended)
.extracting(NewOutboxEvent::eventType)
.containsExactly(WorkLogReservedIntegrationEventMapper.EVENT_TYPE);
assertThat(encoder.drafts())
.singleElement()
.extracting(
draft -> draft.contractId().value(),
draft -> draft.aggregate().aggregateId(),
IntegrationEventDraft::featurePayload)
.containsExactly(
"portfolio.worklog.reserved",
created.id().value(),
new WorkLogReservedPayload(FIXED_ID.value()));
}
@Test
void appendsTheEventInsideTheTransaction() {
// when
createWith(Optional::empty);
create();
// then
assertThat(appendedInsideTransaction)
.as("LegacyOutboxAppendPort.append must run inside tx.inWrite (D2)")
.as("OutboxAppendPort.append must run inside tx.inWrite (D2)")
.containsExactly(true);
}
@Test
void savesAndAppendsInOneWriteTransaction() {
// when
createWith(Optional::empty);
create();
// then
assertThat(tx.committed()).containsExactly(Boundary.WRITE);
}
@Test
void usesTheCreatedWorkLogIdAsTheAggregateId() {
void stampsTheEventIdAndOccurredAtItWasGiven() {
// when
WorkLog created = createWith(Optional::empty);
create();
// then
assertThat(appended)
.extracting(NewOutboxEvent::aggregateId)
.containsExactly(created.id().value());
.extracting(event -> event.eventId().value(), ValidatedIntegrationEvent::occurredAt)
.containsExactly(org.assertj.core.groups.Tuple.tuple(FIXED_EVENT_ID, NOW));
}
@Test
void usesTheEventIdAsTheIdempotencyKey() {
// when
createWith(Optional::empty);
// then
assertThat(appended)
.as("idempotencyKey must equal eventId (I12)")
.extracting(NewOutboxEvent::eventId, NewOutboxEvent::idempotencyKey)
.containsExactly(tuple(FIXED_EVENT_ID, FIXED_EVENT_ID));
}
@Test
void stampsOccurredAtFromTheInjectedClock() {
// when
createWith(Optional::empty);
// then
assertThat(appended).extracting(NewOutboxEvent::occurredAt).containsExactly(NOW);
}
@Test
void writesTheWorkLogIdAndCategoryIntoThePayload() {
// when
createWith(Optional::empty);
// then
assertThat(appended.get(0).payload()).contains(FIXED_ID.value(), "BACKEND");
}
@Test
void fallsBackToTheEventIdAsCorrelationIdWhenNoneIsInContext() {
// when
createWith(Optional::empty);
// then
assertThat(appended)
.as("self-correlation fallback: correlationId = eventId when context is absent")
.extracting(NewOutboxEvent::correlationId)
.containsExactly(FIXED_EVENT_ID);
}
@Test
void usesTheCorrelationIdFromContextWhenPresent() {
// when
createWith(() -> Optional.of("test-corr-123"));
// then
assertThat(appended).extracting(NewOutboxEvent::correlationId).containsExactly("test-corr-123");
}
@Test
void fallsBackToTheEventIdAsCorrelationIdWhenTheContextValueIsBlank() {
// when
createWith(() -> Optional.of(" "));
// then
assertThat(appended).extracting(NewOutboxEvent::correlationId).containsExactly(FIXED_EVENT_ID);
}
private WorkLog createWith(CorrelationIdPort correlation) {
private WorkLog create() {
return new CreateWorkLogUseCase(
new InMemoryWorkLogRepository(),
() -> FIXED_ID,
() -> FIXED_EVENT_ID,
outbox,
correlation,
Clock.fixed(NOW, ZoneOffset.UTC),
new PortfolioEventOutbox(
outbox,
encoder,
() -> FIXED_EVENT_ID,
Optional::empty,
Clock.fixed(NOW, ZoneOffset.UTC)),
tx)
.handle(
new CreateWorkLogCommand(
@@ -7,14 +7,16 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import com.github.f4b6a3.uuid.UuidCreator;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort.Boundary;
import dev.caskeleton.sample.portfolio.application.command.BatchCreateWorkLogsCommand;
import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.command.DeleteWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.command.UpdateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox;
import dev.caskeleton.sample.portfolio.application.exception.WorkLogNotFoundException;
import dev.caskeleton.sample.portfolio.application.exception.WorkLogVersionMismatchException;
import dev.caskeleton.sample.portfolio.application.query.GetWorkLogQuery;
@@ -46,7 +48,7 @@ class WorkLogUseCasesTest {
private static final WorkLogIdFactory IDS =
() -> WorkLogId.of(UuidCreator.getTimeOrderedEpochPlus1().toString());
private static final LegacyOutboxAppendPort NO_OP_OUTBOX = event -> {};
private static final OutboxAppendPort NO_OP_OUTBOX = event -> {};
private static final CorrelationIdPort NO_CORRELATION = Optional::empty;
private final InMemoryWorkLogRepository repository = new InMemoryWorkLogRepository();
@@ -55,10 +57,12 @@ class WorkLogUseCasesTest {
new CreateWorkLogUseCase(
repository,
IDS,
() -> "01FAKEEVENTIDTSV4RRFFQ6900",
NO_OP_OUTBOX,
NO_CORRELATION,
Clock.systemUTC(),
new PortfolioEventOutbox(
NO_OP_OUTBOX,
new FakeIntegrationEventEncoder(),
() -> "01FAKEEVENTIDTSV4RRFFQ6900",
NO_CORRELATION,
Clock.systemUTC()),
tx);
private final UpdateWorkLogUseCase update = new UpdateWorkLogUseCase(repository, tx);
@@ -9,13 +9,14 @@ import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import dev.caskeleton.application.messaging.event.testkit.FakeIntegrationEventEncoder;
import dev.caskeleton.application.observability.CorrelationIdPort;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.NewOutboxEvent;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.application.transaction.testkit.DirectTransactionPort;
import dev.caskeleton.sample.portfolio.application.command.CreateWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.command.DeleteWorkLogCommand;
import dev.caskeleton.sample.portfolio.application.event.PortfolioEventOutbox;
import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase;
import dev.caskeleton.sample.portfolio.application.worklog.DeleteWorkLogUseCase;
import dev.caskeleton.sample.portfolio.domain.worklog.OutboxEventIdFactory;
@@ -219,9 +220,9 @@ class WorkLogAuthorizationContractTest {
}
@Bean
LegacyOutboxAppendPort outboxAppendPort() {
OutboxAppendPort outboxAppendPort() {
// No-op for authorization tests — the contract under test is auth, not outbox.
return (NewOutboxEvent e) -> {};
return event -> {};
}
@Bean
@@ -239,12 +240,20 @@ class WorkLogAuthorizationContractTest {
WorkLogRepository repository,
WorkLogIdFactory idFactory,
OutboxEventIdFactory eventIdFactory,
LegacyOutboxAppendPort outboxAppendPort,
OutboxAppendPort outboxAppendPort,
CorrelationIdPort correlationIdPort,
Clock clock,
TransactionPort tx) {
return new CreateWorkLogUseCase(
repository, idFactory, eventIdFactory, outboxAppendPort, correlationIdPort, clock, tx);
repository,
idFactory,
new PortfolioEventOutbox(
outboxAppendPort,
new FakeIntegrationEventEncoder(),
eventIdFactory,
correlationIdPort,
clock),
tx);
}
@Bean
@@ -48,7 +48,11 @@ import org.springframework.test.web.servlet.ResultActions;
// The slice excludes the data layer; persistence-jpa is on while present, so it is switched off.
@SpringBootTest(
classes = SamplePublicAccessSecurityConfigTest.TestBootstrap.class,
properties = "ca-skeleton.persistence-jpa.enabled=false")
properties = {
"ca-skeleton.persistence-jpa.enabled=false",
// The PostgreSQL idempotency store needs the relational module this test leaves off.
"ca-skeleton.capabilities.idempotency.provider=disabled"
})
@AutoConfigureMockMvc
class SamplePublicAccessSecurityConfigTest {
@@ -62,7 +62,11 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean;
classes = OpenApiDriftContractTest.OpenApiDriftTestApp.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
// The app excludes the data layer; persistence-jpa is on while present, so it is switched off.
properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"})
properties = {
"management.server.port=0",
"ca-skeleton.persistence-jpa.enabled=false",
"ca-skeleton.capabilities.idempotency.provider=disabled"
})
@AutoConfigureTestRestTemplate
class OpenApiDriftContractTest {
@@ -34,7 +34,11 @@ import org.springframework.web.bind.annotation.RestController;
classes = DateHeaderContractTest.DateProbeApp.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
// The app excludes the data layer; persistence-jpa is on while present, so it is switched off.
properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"})
properties = {
"management.server.port=0",
"ca-skeleton.persistence-jpa.enabled=false",
"ca-skeleton.capabilities.idempotency.provider=disabled"
})
@AutoConfigureTestRestTemplate
class DateHeaderContractTest {
@@ -64,7 +64,8 @@ import org.springframework.web.bind.annotation.RestController;
"spring.jackson.deserialization.fail-on-unknown-properties=true",
"management.server.port=0",
// The app excludes the data layer; persistence-jpa is on while present, so it is off here.
"ca-skeleton.persistence-jpa.enabled=false"
"ca-skeleton.persistence-jpa.enabled=false",
"ca-skeleton.capabilities.idempotency.provider=disabled"
})
@AutoConfigureTestRestTemplate
class VirtualThreadMdcE2ETest {
@@ -44,7 +44,11 @@ import tools.jackson.databind.ObjectMapper;
classes = OpenApiSnapshotTest.OpenApiTestApp.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
// The app excludes the data layer; persistence-jpa is on while present, so it is switched off.
properties = {"management.server.port=0", "ca-skeleton.persistence-jpa.enabled=false"})
properties = {
"management.server.port=0",
"ca-skeleton.persistence-jpa.enabled=false",
"ca-skeleton.capabilities.idempotency.provider=disabled"
})
@AutoConfigureTestRestTemplate
class OpenApiSnapshotTest {