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
+93
View File
@@ -0,0 +1,93 @@
# composition:idempotency — 요청 멱등성 executor 조립
- Module ID: `composition-idempotency`
- Gradle path: `:composition:idempotency`
- Package: `dev.caskeleton.composition.idempotency`
- 테스트: `./gradlew :composition:idempotency:test --console=plain`
## 제공하는 것
선택한 provider의 저장소 위에 `IdempotencyExecutor`를 하나 만든다. KEYED use case는
application-core의 `IdempotencyExecutor`만 받는다.
```
composition:idempotency
├─ IdempotencyAutoConfiguration provider != disabled 일 때만: 설정 바인딩 + executor 하나
├─ IdempotencySettings 수명 정책(lease·replay TTL·retention·codec·revision), strict 바인딩
└─ config/module-defaults/idempotency.yml (설정 기본값, support 로더가 읽음)
```
- 저장소는 포트(`IdempotencyStorePort`)다. Redis는 `adapter:outbound:cache-redis`, PostgreSQL은
`adapter:outbound:persistence-jpa`가 `ca-skeleton.capabilities.idempotency.provider`에 따라 하나를
기여한다. 선택한 provider의 저장소가 정확히 하나가 아니면(0개: 모듈이 없거나 꺼짐, 2개: 다른
곳이 하나 더 등록) 기동이 개수와 함께 실패한다.
- 켜기와 끄기: 모듈이 있어도 `provider=disabled`(기본)면 아무것도 바인딩하거나 만들지 않는다.
- 설정 바인딩은 `StrictSettingsBinder`다. 같은 prefix 아래 Redis 저장소가 자기 키(`key-version`,
`command-timeout`)를 두므로 그 두 키만 빼고 엄격하게 본다. 수명 정책 키를 잘못 쓰면 기본값이
조용히 쓰이는 대신 기동이 실패한다.
- app-bootstrap과 sample-portfolio가 같은 한 줄을 쓴다. 예전의 sample 복사본
(`SampleIdempotencyConfig`, 상한 검증 없이 `Binder`로 읽고 저장소를 하나로 가정)은 삭제했다.
## 추가할 한 줄
```groovy
// app-bootstrap/build.gradle (sample-portfolio/build.gradle 도 같다)
runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor
```
기본 조립에 있다. provider가 `disabled`면 꺼져 있으므로 저장소 모듈 없이도 안전하다. 이 줄을 지우면
executor, 설정 기본값이 함께 빠진다(그때 KEYED use case는 executor를 받지 못해 기동이 실패한다).
## 필요한 env 키
전체 목록과 타입은 `docs/registries/env-keys.yaml`의 `APP_IDEMPOTENCY_*` 행이 SSOT다.
| 언제 | 키 |
| --- | --- |
| 켤 때 | `APP_IDEMPOTENCY_PROVIDER` (`redis` 또는 `postgresql`), 그리고 그 provider 모듈의 줄과 env |
| 조정할 때 | `APP_IDEMPOTENCY_PROCESSING_LEASE`(≤1h), `APP_IDEMPOTENCY_TTL`(≤72h), `APP_IDEMPOTENCY_FAILURE_RETENTION`(≤30d) |
## 설계 결정 참조 (app-bootstrap에서 옮김)
이 모듈의 코드는 2026-09-28에 app-bootstrap `autoconfigure/idempotency`에서 옮겨 왔다(소유자 결정 3). 아래 근거는 그때의 기록이다.
### IdempotencyAutoConfiguration
- **`IdempotencyExecutor`를 여기서 한 번만 만든다.** provider 모듈은 `IdempotencyStorePort`만
내놓는다 — `redis`는 `cache-redis`의 `RedisIdempotencyConfig`, `postgresql`은 `persistence-jpa`의
`PostgreSqlIdempotencyStoreConfig`. lease·replay TTL·retention·codec id·policy revision 은 어느
store 든 같은 정책이라 `IdempotencySettings` 하나에서 읽는다. executor 를 application-core 밖에서
만드는 이유는 이 설정을 `application-core`가 직접 읽으면 안 되기 때문이다.
- **store 가 정확히 하나가 아니면 기동을 거부한다.** 0개는 provider 모듈이 runtime classpath 에
없거나 스위치가 꺼진 경우, 2개는 다른 무언가가 store 를 등록한 경우다. 둘 다 빈 누락 오류나 엉뚱한
store 로 요청을 처리하는 대신 개수를 담은 startup 실패로 드러난다.
- `provider=disabled`(기본)면 executor 빈 자체가 없다. `jdbc` 값과 V1 조립(`IdempotencyConfig`,
`config/idempotency.yml`)은 삭제됐다.
- `postgresql` provider 는 PostgreSQL data source 가 아니면 기동을 거부한다. `bootRunH2` 에서는
`disabled` 나 `redis` 를 쓴다.
### IdempotencySettings
- `ca-skeleton.capabilities.idempotency` 에 바인딩되는 유일한 설정 record 다(값은
`config/module-defaults/idempotency.yml`).
| 키 | env | 기본값 | 상한 |
| --- | --- | --- | --- |
| `provider` | `APP_IDEMPOTENCY_PROVIDER` | `disabled` | `disabled` \| `redis` \| `postgresql` |
| `processing-lease` | `APP_IDEMPOTENCY_PROCESSING_LEASE` | 30s | 1h |
| `replay-ttl` | `APP_IDEMPOTENCY_TTL` | 24h | 72h |
| `failure-retention` | `APP_IDEMPOTENCY_FAILURE_RETENTION` | 24h | 30d |
| `response-codec-id` | — | `json-v2` | 1–64자 |
| `policy-revision` | — | 2 | 양수 |
| `reaper-interval` | — | 10m | 양수 |
Redis store 튜닝값 `key-version`, `command-timeout`(`APP_IDEMPOTENCY_REDIS_COMMAND_TIMEOUT`)도
같은 prefix 아래 있지만 lifecycle 정책이 아니라서 이 record 에 두지 않고 `cache-redis`가 읽는다.
- **상한 검사는 컴팩트 생성자에서 fail-fast 로 던진다.** `Duration`의 상한은 JSR-303(`@Valid`)
애너테이션으로 표현할 수 없어 생성자에서 직접 검증한다. 검증을 느슨하게 두면 과도하게 긴 TTL 이
저장소를 조용히 부풀리고 멱등성 키 추측 공격의 유효 시간 창을 넓히기 때문에, 부팅 시점에 즉시
실패시키는 쪽을 택했다.
- **replay TTL 상한(72h) / 기본값(24h)을 바꿀 때는 보안 베이스라인의 JWT 키 회전 겹침(overlap)
윈도와 반드시 함께 검토해야 한다.** 멱등성 레코드의 수명이 키 회전 겹침 윈도(현재 24h)보다 길면,
가명화(pseudonym) 기준이 회전된 principal 에 대해 레코드가 재생(replay)될 수 있다. 이 불변식을
강제하는 CI 게이트는 security-operational-baseline 쪽에 위임돼 있다.
- **`reaper-interval`은 전용 환경변수가 없다.** reaper 실행 주기는 비밀이나 배포별 값이 아니라 순수
운영 튜닝 값이다. reaper 는 provider 가 `postgresql` 일 때만 돈다.
+35
View File
@@ -0,0 +1,35 @@
plugins {
id 'ca.spring-library'
id 'ca.spring-config'
}
// The request-idempotency composition, selected by one line in a composition root:
//
// runtimeOnly project(':composition:idempotency')
//
// It builds the one IdempotencyExecutor over whichever IdempotencyStorePort the selected provider
// contributes (Redis from cache-redis, PostgreSQL from persistence-jpa), and ships the lifecycle
// settings (config/module-defaults/idempotency.yml). It names no provider module: the store is a
// port. app-bootstrap and sample-portfolio take the same line, so the executor is built one way.
//
// Not a composition root: it composes one capability and does not run. Same shape as
// :composition:notification-platform.
dependencies {
implementation project(':application-core')
// StrictSettingsBinder and the typed startup failures.
implementation project(':adapter:outbound:support')
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework:spring-context'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
// The executor tests drive the port owner's shared fake store.
testImplementation testFixtures(project(':application-core'))
// IdempotencyAutoConfigurationTest composes the real PostgreSQL provider configuration, so a
// selection that stops reaching it shows up here. Test scope only: nothing in main names it.
testRuntimeOnly project(':adapter:outbound:persistence-jpa')
testImplementation 'org.springframework:spring-jdbc'
testImplementation 'org.mockito:mockito-core'
// IdempotencyModuleDefaultsTest reads the shipped file through the loader that serves it.
testRuntimeOnly 'org.yaml:snakeyaml'
}
+199
View File
@@ -0,0 +1,199 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath
ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-core:2.21.5=testRuntimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.21.5=testRuntimeClasspath
com.fasterxml.jackson:jackson-bom:2.21.5=testRuntimeClasspath
com.fasterxml:classmate:1.7.3=testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
com.google.code.gson:gson:2.13.2=spotbugs
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.38.0=testCompileClasspath
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h2database:h2:2.4.240=testRuntimeClasspath
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.sun.istack:istack-commons-runtime:4.1.2=testRuntimeClasspath
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath
com.zaxxer:HikariCP:7.0.2=testRuntimeClasspath
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-core:1.16.7=testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.projectreactor:reactor-core:3.8.7=testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath
jakarta.inject:jakarta.inject-api:2.0.1=testRuntimeClasspath
jakarta.persistence:jakarta.persistence-api:3.2.0=testRuntimeClasspath
jakarta.transaction:jakarta.transaction-api:2.0.1=testRuntimeClasspath
jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
net.logstash.logback:logstash-logback-encoder:8.0=testRuntimeClasspath
net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle,testRuntimeClasspath
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.commons:commons-text:1.3=checkstyle
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.logging.log4j:log4j-to-slf4j:2.25.5=testCompileClasspath,testRuntimeClasspath
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.aspectj:aspectjweaver:1.9.25.1=testRuntimeClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath
org.checkerframework:checker-qual:3.55.1=testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.eclipse.angus:angus-activation:2.0.3=testRuntimeClasspath
org.flywaydb:flyway-core:11.14.1=testRuntimeClasspath
org.flywaydb:flyway-database-postgresql:11.14.1=testRuntimeClasspath
org.glassfish.jaxb:jaxb-core:4.0.9=testRuntimeClasspath
org.glassfish.jaxb:jaxb-runtime:4.0.9=testRuntimeClasspath
org.glassfish.jaxb:txw2:4.0.9=testRuntimeClasspath
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hdrhistogram:HdrHistogram:2.2.2=testRuntimeClasspath
org.hibernate.models:hibernate-models:1.0.1=testRuntimeClasspath
org.hibernate.orm:hibernate-core:7.2.24.Final=testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
org.jboss.logging:jboss-logging:3.6.3.Final=testRuntimeClasspath
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.latencyutils:LatencyUtils:2.0.3=testRuntimeClasspath
org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath
org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath
org.osgi:org.osgi.resource:1.0.0=testCompileClasspath
org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.postgresql:postgresql:42.7.13=testRuntimeClasspath
org.reactivestreams:reactive-streams:1.0.4=testRuntimeClasspath
org.reflections:reflections:0.10.2=checkstyle
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.18=runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor
org.springframework.boot:spring-boot-data-commons:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-data-jpa:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-flyway:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-hibernate:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jdbc:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-jpa:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-persistence:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-sql:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-starter-data-jpa:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-starter-flyway:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jdbc:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-starter-logging:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-transaction:4.0.8=testRuntimeClasspath
org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.data:spring-data-commons:4.0.7=testRuntimeClasspath
org.springframework.data:spring-data-jpa:4.0.7=testRuntimeClasspath
org.springframework.integration:spring-integration-core:7.0.6=testRuntimeClasspath
org.springframework.integration:spring-integration-jdbc:7.0.6=testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aspects:7.0.9=testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-jdbc:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-messaging:7.0.9=testRuntimeClasspath
org.springframework:spring-orm:7.0.9=testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-tx:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath
org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath
empty=
@@ -0,0 +1,66 @@
package dev.caskeleton.composition.idempotency;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import dev.caskeleton.application.idempotency.IdempotencyExecutor;
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/**
* Assembles the request-idempotency executor, once, for whichever provider is selected.
*
* <p>Providers contribute only an {@link IdempotencyStorePort}: Redis from {@code
* adapter:outbound:cache-redis}, PostgreSQL from {@code adapter:outbound:persistence-jpa}, each
* conditional on {@code ca-skeleton.capabilities.idempotency.provider}. The lifecycle policy —
* lease, replay TTL, retention, codec id, policy revision — is the same whichever store holds the
* records, so it lives in one {@link IdempotencySettings} record and the executor is built here
* from it. Every composition root that serves idempotent requests takes this module rather than a
* copy of it: the application and the sample build the same executor from the same checks.
*
* <p>A selected provider must yield exactly one store. None means the provider's module is not on
* the runtime classpath or its switch is off; two means something else registered one (a scan-found
* stereotype, a hand-written bean). Either is refused at startup with the count, rather than
* surfacing as an unsatisfied dependency or as requests served by the wrong store. The store is
* looked up when the executor is built, not when this class is evaluated, so no ordering against
* the provider modules is needed.
*
* <p>{@code provider=disabled} (the default) is the off switch: nothing is bound or built.
*/
@AutoConfiguration
@ConditionalOnExpression(
"!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()"
+ ".equalsIgnoreCase('disabled')")
public class IdempotencyAutoConfiguration {
@Bean
IdempotencySettings idempotencySettings(Environment environment) {
return IdempotencySettings.bind(environment);
}
@Bean
IdempotencyExecutor idempotencyExecutor(
ObjectProvider<IdempotencyStorePort> stores, IdempotencySettings settings) {
List<IdempotencyStorePort> found = stores.orderedStream().toList();
if (found.size() != 1) {
throw StartupFailures.requiredAdapterDisabled(
"ca-skeleton.capabilities.idempotency.provider="
+ settings.provider().name().toLowerCase(Locale.ROOT)
+ " needs exactly one IdempotencyStorePort, but found "
+ found.size()
+ ". Add the provider's module to the runtime classpath and enable it, and make sure"
+ " nothing else registers a store.");
}
return new IdempotencyExecutor(
found.get(0),
settings.processingLease(),
settings.replayTtl(),
settings.failureRetention(),
settings.responseCodecId(),
settings.policyRevision());
}
}
@@ -0,0 +1,111 @@
package dev.caskeleton.composition.idempotency;
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import java.time.Duration;
import java.util.Set;
import org.springframework.core.env.Environment;
/**
* The one settings record for request idempotency, bound at {@code
* ca-skeleton.capabilities.idempotency}. The executor is built from it once, whichever provider
* supplies the store. Every value is checked here, so a bad value fails startup rather than the
* first request.
*
* <p>The Redis store reads its own two knobs ({@code key-version}, {@code command-timeout}) under
* the same prefix; they are store tuning, not lifecycle policy, so they are not repeated here. The
* binding is strict for everything else under the prefix: a misspelt lifecycle key fails startup
* instead of leaving its default silently in force.
*
* @param provider which store is composed: {@code disabled}, {@code redis} or {@code postgresql}
* @param processingLease how long one attempt holds a claim before another may take it over
* @param replayTtl how long a completed response is replayable (at most 72h, D6)
* @param failureRetention how long a failed attempt's evidence is kept
* @param responseCodecId identifier of the codec the stored payload is written with
* @param policyRevision replay policy revision written into and compared on each record
* @param reaperInterval how often the PostgreSQL provider purges expired rows
*/
public record IdempotencySettings(
Provider provider,
Duration processingLease,
Duration replayTtl,
Duration failureRetention,
String responseCodecId,
Integer policyRevision,
Duration reaperInterval) {
static final String PREFIX = "ca-skeleton.capabilities.idempotency";
/** Keys under the prefix that the Redis store binds for itself. */
static final Set<String> STORE_OWNED_KEYS = Set.of("key-version", "command-timeout");
private static final Duration MAX_PROCESSING_LEASE = Duration.ofHours(1);
private static final Duration MAX_REPLAY_TTL = Duration.ofDays(3);
private static final Duration MAX_FAILURE_RETENTION = Duration.ofDays(30);
public IdempotencySettings {
provider = provider == null ? Provider.DISABLED : provider;
processingLease =
bounded(
"processing-lease",
orDefault(processingLease, Duration.ofSeconds(30)),
MAX_PROCESSING_LEASE);
replayTtl = bounded("replay-ttl", orDefault(replayTtl, Duration.ofHours(24)), MAX_REPLAY_TTL);
failureRetention =
bounded(
"failure-retention",
orDefault(failureRetention, Duration.ofHours(24)),
MAX_FAILURE_RETENTION);
reaperInterval =
bounded("reaper-interval", orDefault(reaperInterval, Duration.ofMinutes(10)), null);
responseCodecId = responseCodecId == null ? "json-v2" : responseCodecId;
if (responseCodecId.isBlank() || responseCodecId.length() > 64) {
throw StartupFailures.envValidation(
PREFIX
+ ".response-codec-id must contain 1-64 characters, was '"
+ responseCodecId
+ "'");
}
policyRevision = policyRevision == null ? 2 : policyRevision;
if (policyRevision < 1) {
throw StartupFailures.envValidation(
PREFIX + ".policy-revision must be positive, was " + policyRevision);
}
}
/**
* Binds the prefix strictly, leaving the store's own keys to the store.
*
* @param environment the environment to bind from
* @return the validated settings
*/
public static IdempotencySettings bind(Environment environment) {
return StrictSettingsBinder.bindExcept(
environment, PREFIX, IdempotencySettings.class, STORE_OWNED_KEYS);
}
private static Duration orDefault(Duration value, Duration fallback) {
return value == null ? fallback : value;
}
private static Duration bounded(String key, Duration value, Duration maximum) {
if (value.isZero() || value.isNegative()) {
throw StartupFailures.envValidation(PREFIX + "." + key + " must be positive, was " + value);
}
if (maximum != null && value.compareTo(maximum) > 0) {
throw StartupFailures.envValidation(
PREFIX + "." + key + " must be at most " + maximum + ", was " + value);
}
return value;
}
/** The stores a deployment may select; never inferred from the classpath. */
public enum Provider {
/** No store and no executor: the capability is off. */
DISABLED,
/** The Redis owner-safe store (adapter:outbound:cache-redis). */
REDIS,
/** The PostgreSQL owner-safe store (adapter:outbound:persistence-jpa). */
POSTGRESQL
}
}
@@ -0,0 +1 @@
dev.caskeleton.composition.idempotency.IdempotencyAutoConfiguration
@@ -0,0 +1,20 @@
# 멱등성 제공자 선택과 수명 정책의 설정 기본값. Redis 역할(cache/rate-limit/lease)과 Redis 저장소
# 튜닝(key-version, command-timeout)은 cache-redis 모듈이 config/module-defaults/cache-redis.yml 로
# 가져온다.
#
# adapter:outbound:support 의 ModuleDefaultsEnvironmentPostProcessor 가 읽는다. 우선순위는 가장 낮아서
# application*.yml, 환경 변수, 시스템 속성이 항상 이긴다. 이 모듈을 빌드에서 빼면 이 파일도 함께
# 빠진다.
ca-skeleton:
capabilities:
idempotency:
# disabled | redis | postgresql. Exactly one store; the executor is built once over it from
# the lifecycle keys below, whichever provider is selected. disabled binds and builds nothing.
provider: ${APP_IDEMPOTENCY_PROVIDER:disabled}
# Lifecycle policy (IdempotencySettings), the same whichever provider holds the records.
processing-lease: ${APP_IDEMPOTENCY_PROCESSING_LEASE:30s}
replay-ttl: ${APP_IDEMPOTENCY_TTL:24h}
failure-retention: ${APP_IDEMPOTENCY_FAILURE_RETENTION:24h}
response-codec-id: json-v2
# Numeric: the owner-safe claim writes this into the record and compares it there.
policy-revision: 2
@@ -0,0 +1,126 @@
package dev.caskeleton.composition.idempotency;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.idempotency.IdempotencyExecutor;
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
import dev.caskeleton.application.idempotency.testkit.InMemoryIdempotencyStore;
import java.time.Clock;
import java.util.Arrays;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcOperations;
/**
* What each provider selection composes, counted: one executor over exactly one store, or nothing.
*
* <p>The PostgreSQL case uses the real persistence-jpa provider configuration, so a selection that
* stops reaching it shows up here. The Redis store needs a live runtime owner, so a stand-in store
* plays it; what is under test is that the composition root builds the executor once, not the
* store. The component scan of the PostgreSQL store package is included in every case, pinning the
* old regression where a stereotype on the store registered it under every selection.
*/
class IdempotencyAutoConfigurationTest {
private static final String POSTGRESQL_STORE_CONFIG =
"dev.caskeleton.adapter.outbound.persistence.autoconfigure.PostgreSqlIdempotencyStoreConfig";
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(IdempotencyAutoConfiguration.class))
.withUserConfiguration(ScannedPersistence.class, postgreSqlStoreConfig())
.withBean(JdbcOperations.class, () -> org.mockito.Mockito.mock(JdbcOperations.class))
.withBean(Clock.class, Clock::systemUTC)
// The schema stream talks to a real database; its own integration test covers it.
.withPropertyValues("ca-skeleton.runtime.migration-on-startup=false");
@Test
void disabledComposesNoExecutorEvenWithAStorePresent() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=disabled")
.withBean(IdempotencyStorePort.class, InMemoryIdempotencyStore::new)
.run(
context ->
assertThat(context).hasNotFailed().doesNotHaveBean(IdempotencyExecutor.class));
}
@Test
void redisComposesOneExecutorOverTheRedisStoreAlone() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis")
.withBean(IdempotencyStorePort.class, InMemoryIdempotencyStore::new)
.run(
context ->
assertThat(context)
.hasNotFailed()
.hasSingleBean(IdempotencyExecutor.class)
.getBean(IdempotencyStorePort.class)
.isInstanceOf(InMemoryIdempotencyStore.class));
}
@Test
void postgresqlComposesOneExecutorOverThePersistenceJpaStore() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=postgresql")
.run(
context ->
assertThat(context)
.hasNotFailed()
.hasSingleBean(IdempotencyExecutor.class)
.getBean(IdempotencyStorePort.class)
.extracting(store -> store.getClass().getSimpleName())
.isEqualTo("PostgreSqlOwnerSafeIdempotencyStore"));
}
@Test
@DisplayName("a selected provider whose module contributed no store fails startup with the count")
void selectedProviderWithoutAStoreFailsStartup() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=redis")
.run(
context ->
assertThat(context)
.hasFailed()
.getFailure()
.hasStackTraceContaining(
"provider=redis needs exactly one IdempotencyStorePort")
.hasStackTraceContaining("found 0"));
}
@Test
@DisplayName("a second store beside the selected one fails startup with the count")
void secondStoreBesideTheSelectedOneFailsStartup() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=postgresql")
.withBean("strayStore", IdempotencyStorePort.class, InMemoryIdempotencyStore::new)
.run(
context ->
assertThat(context).hasFailed().getFailure().hasStackTraceContaining("found 2"));
}
@Test
void theIdempotencyCompositionDoesNotOwnTheApplicationClock() {
assertThat(Arrays.stream(IdempotencyAutoConfiguration.class.getDeclaredMethods()))
.noneMatch(
method ->
method.getReturnType() == Clock.class && method.isAnnotationPresent(Bean.class));
}
private static Class<?> postgreSqlStoreConfig() {
try {
return Class.forName(POSTGRESQL_STORE_CONFIG);
} catch (ClassNotFoundException missing) {
throw new IllegalStateException(missing);
}
}
/** What the composition root once scanned, narrowed to the store package. */
@Configuration(proxyBeanMethods = false)
@ComponentScan("dev.caskeleton.adapter.outbound.persistence.idempotency.postgresql")
static class ScannedPersistence {}
}
@@ -0,0 +1,64 @@
package dev.caskeleton.composition.idempotency;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.ModuleDefaultsEnvironmentPostProcessor;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.annotation.ImportCandidates;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.StandardEnvironment;
/**
* The module arrives with its own registration and settings, and a deployment's value beats them.
*/
class IdempotencyModuleDefaultsTest {
@Test
void theModuleRegistersItsAutoConfiguration() {
assertThat(ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()))
.contains(IdempotencyAutoConfiguration.class.getName());
}
@Test
void theShippedDefaultsLeaveIdempotencyOff() {
// when
StandardEnvironment environment = processed(Map.of());
// then
assertThat(environment.getProperty("ca-skeleton.capabilities.idempotency.provider"))
.isEqualTo("disabled");
}
@Test
void theEnvironmentVariableSelectsTheProviderThroughTheShippedPlaceholder() {
// when
StandardEnvironment environment = processed(Map.of("APP_IDEMPOTENCY_PROVIDER", "postgresql"));
// then
assertThat(environment.getProperty("ca-skeleton.capabilities.idempotency.provider"))
.isEqualTo("postgresql");
}
@Test
void theShippedLifecycleKeysBindWithoutAStrayKey() {
// given
StandardEnvironment environment = processed(Map.of("APP_IDEMPOTENCY_PROVIDER", "redis"));
// when
IdempotencySettings settings = IdempotencySettings.bind(environment);
// then
assertThat(settings.responseCodecId()).isEqualTo("json-v2");
}
private static StandardEnvironment processed(Map<String, Object> deployment) {
StandardEnvironment environment = new StandardEnvironment();
environment.getPropertySources().addFirst(new MapPropertySource("deployment", deployment));
new ModuleDefaultsEnvironmentPostProcessor()
.postProcessEnvironment(environment, new SpringApplication());
return environment;
}
}
@@ -0,0 +1,189 @@
package dev.caskeleton.composition.idempotency;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.time.Duration;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.boot.context.properties.bind.BindException;
import org.springframework.mock.env.MockEnvironment;
class IdempotencySettingsTest {
private static final String PREFIX = "ca-skeleton.capabilities.idempotency.";
@Test
void absentLifecycleKeysBindToTheDocumentedDefaults() {
// given
MockEnvironment environment = new MockEnvironment().withProperty(PREFIX + "provider", "redis");
// when
IdempotencySettings settings = IdempotencySettings.bind(environment);
// then
assertThat(settings)
.usingRecursiveComparison()
.isEqualTo(
new IdempotencySettings(
IdempotencySettings.Provider.REDIS,
Duration.ofSeconds(30),
Duration.ofHours(24),
Duration.ofHours(24),
"json-v2",
2,
Duration.ofMinutes(10)));
}
@Test
void kebabCaseKeysBindEveryField() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty(PREFIX + "provider", "postgresql")
.withProperty(PREFIX + "processing-lease", "45s")
.withProperty(PREFIX + "replay-ttl", "72h")
.withProperty(PREFIX + "failure-retention", "2h")
.withProperty(PREFIX + "response-codec-id", "json-v3")
.withProperty(PREFIX + "policy-revision", "3")
.withProperty(PREFIX + "reaper-interval", "1m");
// when
IdempotencySettings settings = IdempotencySettings.bind(environment);
// then
assertThat(settings)
.usingRecursiveComparison()
.isEqualTo(
new IdempotencySettings(
IdempotencySettings.Provider.POSTGRESQL,
Duration.ofSeconds(45),
Duration.ofHours(72),
Duration.ofHours(2),
"json-v3",
3,
Duration.ofMinutes(1)));
}
@Test
void anUnknownProviderFailsBinding() {
// given
MockEnvironment environment = new MockEnvironment().withProperty(PREFIX + "provider", "jdbc");
// when
Throwable thrown = catchThrowable(() -> IdempotencySettings.bind(environment));
// then
assertThat(thrown)
.isInstanceOf(BindException.class)
.hasStackTraceContaining("ca-skeleton.capabilities.idempotency.provider");
}
/**
* A misspelt lifecycle key used to bind to nothing and leave the default in force: {@code
* replay-tll=1h} ran with a 24-hour replay window.
*/
@Test
void aMisspeltLifecycleKeyFailsBindingInsteadOfLeavingTheDefaultInForce() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty(PREFIX + "provider", "redis")
.withProperty(PREFIX + "replay-tll", "1h");
// when
Throwable thrown = catchThrowable(() -> IdempotencySettings.bind(environment));
// then
assertThat(thrown).isInstanceOf(BindException.class).hasStackTraceContaining("replay-tll");
}
@Test
void theRedisStoresOwnKeysUnderTheSharedPrefixAreLeftToTheStore() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty(PREFIX + "provider", "redis")
.withProperty(PREFIX + "key-version", "1")
.withProperty(PREFIX + "command-timeout", "200ms");
// when
IdempotencySettings settings = IdempotencySettings.bind(environment);
// then
assertThat(settings.provider()).isEqualTo(IdempotencySettings.Provider.REDIS);
}
@ParameterizedTest
@DisplayName("an out-of-range duration is refused with its key and bound")
@CsvSource({
"PT0S, PT24H, PT24H, PT10M, processing-lease must be positive",
"PT61M, PT24H, PT24H, PT10M, processing-lease must be at most PT1H",
"PT30S, PT73H, PT24H, PT10M, replay-ttl must be at most PT72H",
"PT30S, -PT1H, PT24H, PT10M, replay-ttl must be positive",
"PT30S, PT24H, P31D, PT10M, failure-retention must be at most PT720H",
"PT30S, PT24H, PT24H, PT0S, reaper-interval must be positive"
})
void outOfRangeDurationIsRefused(
Duration lease, Duration replay, Duration retention, Duration reaper, String message) {
// when
Throwable thrown =
catchThrowable(
() ->
new IdempotencySettings(
IdempotencySettings.Provider.REDIS,
lease,
replay,
retention,
null,
null,
reaper));
// then
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("ca-skeleton.capabilities.idempotency." + message);
}
@ParameterizedTest
@CsvSource({"'', response-codec-id must contain 1-64 characters", "' ', response-codec-id"})
void blankCodecIdIsRefused(String codecId, String message) {
// when
Throwable thrown =
catchThrowable(
() ->
new IdempotencySettings(
IdempotencySettings.Provider.REDIS, null, null, null, codecId, null, null));
// then
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("ca-skeleton.capabilities.idempotency." + message);
}
@Test
void nonPositivePolicyRevisionIsRefused() {
// when
Throwable thrown =
catchThrowable(
() ->
new IdempotencySettings(
IdempotencySettings.Provider.REDIS, null, null, null, null, 0, null));
// then
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining(
"ca-skeleton.capabilities.idempotency.policy-revision must be positive");
}
}
+137
View File
@@ -0,0 +1,137 @@
# composition:outbox-relay — transactional outbox relay 조립
- Module ID: `composition-outbox-relay`
- Gradle path: `:composition:outbox-relay`
- Package: `dev.caskeleton.composition.outbox`
- 테스트: `./gradlew :composition:outbox-relay:test --console=plain`
## 제공하는 것
outbox에 쌓인 event를 broker로 내보내는 relay를 조립한다. use case는 이 모듈을 부르지 않는다 —
use case는 `OutboxAppendPort`로 append만 하고, relay가 나머지를 한다.
```
composition:outbox-relay
└─ OutboxRelayAutoConfiguration ca-skeleton.outbox.enabled=true + OutboxStorePort 가 있을 때만
├─ OutboxSettings ca-skeleton.outbox.* strict 바인딩(오타는 기동 실패)
├─ OutboxRelayScheduler relay-enabled=true + OutboxMessagePublishPort 가 있을 때만,
│ PublishPendingOutboxEventsUseCase 를 fixed-delay 로 구동
├─ OutboxMetrics outbox.pending.size / outbox.publisher.lag / published.total
└─ OutboxLeaderElectionToken SKIP LOCKED 가 리더 선출이라는 표시(로직 없음)
```
- 조립 순서: `PersistenceJpaAutoConfiguration`(store)과 `MessagingBridgeRootAutoConfiguration`(발행
포트) 뒤에 온다(`afterName`, 문자열이라 컴파일 의존이 없다). 둘 다 포트라서 이 모듈은 어떤 모듈
타입도 이름으로 부르지 않는다.
- 발행 포트가 없으면 스케줄러를 만들지 않는다. messaging을 고르지 않은 배포는 PENDING row를 그대로
둔다(대역 publisher로 DEAD까지 소진하지 않는다).
- persistence-jpa 안이 아니라 여기 있는 이유: driven adapter는 use case를 만들거나 부르지 않는다
(ArchUnit `PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES`).
- 설정 기본값: `ca-skeleton.outbox.*`의 기본값은 store를 가진 persistence-jpa가
`config/module-defaults/persistence-jpa.yml`로 싣는다(store와 reaper도 `enabled`,
`reaper-interval`, `published-retention`을 읽는다). 키의 선언과 검증은 이 모듈의 `OutboxSettings`
하나다.
## 추가할 한 줄
```groovy
// app-bootstrap/build.gradle
runtimeOnly project(':composition:outbox-relay') // outbox relay
```
기본 조립에 있다. store(persistence-jpa + `APP_OUTBOX_ENABLED=true`)가 없으면 아무것도 만들지 않으므로
안전하다. 이 줄을 지우면 relay, metrics가 함께 빠진다(append한 row는 발행되지 않고 남는다).
## 필요한 env 키
전체 목록과 타입은 `docs/registries/env-keys.yaml`의 `APP_OUTBOX_*` 행이 SSOT다.
| 언제 | 키 |
| --- | --- |
| 항상 | persistence-jpa 줄과 그 연결 env, `APP_OUTBOX_ENABLED=true` |
| relay를 돌릴 때 | `APP_OUTBOX_RELAY_ENABLED=true`, 그리고 발행 capability(`adapter:outbound:messaging-kafka` 줄과 `APP_MESSAGING_PRODUCER_ID`, `APP_MESSAGING_KAFKA_BROKERS`) |
poll 주기·batch 크기·in-flight timeout·보존 기간은 env 키 없이 `ca-skeleton.outbox.*` 기본값으로
동작한다.
## 설계 결정 참조 (app-bootstrap에서 옮김)
이 모듈의 코드는 2026-09-28에 app-bootstrap `autoconfigure/outbox`에서 옮겨 왔다(소유자 결정 3). 아래 근거는 그때의 기록이다. `OutboxSettings`는 이제 strict 바인딩이고 `enabled`도 선언한다.
### OutboxRelayAutoConfiguration
- **릴레이 use case 를 `@Service`가 아니라 이 모듈에서 수동 조립한다.**
`PublishPendingOutboxEventsUseCase`는 `batchSize`와 `inFlightTimeout` 같은 설정값을 생성자로 받아야
하는데, `application-core`는 설정(`OutboxSettings`)을 직접 읽으면 안 된다. 그래서 설정을 볼 수 있는
조립 모듈(`OutboxRelayAutoConfiguration`)이 값을 꺼내 use case 를 손으로 만들어 넘긴다. use case 클래스의
`@UseCaseCapability` 애너테이션은 와이어링 방식과 무관하게 유지된다(ArchUnit 이 강제).
- **이 모듈은 failure reporter를 구현하지 않고 주입만 한다.** messaging bridge의 `MessagingConfig`가
정확히 하나의 `OutboxRelayFailureReportPort` 구현을 만들고, `OutboxRelayAutoConfiguration`은 이를
relay 생성자에 전달한다.
- **릴레이 use case 를 독립 컨텍스트 빈으로 등록하지 않는다.** 만약 빈으로 올리면 `adapter-web`의
`MethodSecurityConfig` 메서드 보안 pointcut(`@RequiresPermission`)이 이 타입을 CGLIB 프록시로
감싼다. 그런데 use case 가 `final` 클래스라 프록시 생성 자체가 실패하고, 설령 된다 해도 스케줄러
스레드에는 `Authentication`이 없어 매 릴레이 틱이 fail-closed 로 거부된다. 그래서 빈으로 올리지
않고, `outbox:relay` 권한 확인은 스케줄러 컨텍스트에서 관례로 둔다.
- **`outboxRelayScheduler` 빈은 `ca-skeleton.outbox.relay-enabled=true`일 때만 만든다(기본
false).** 키가 없으면 꺼진 것으로 본다. 모듈 기본값(`persistence-jpa.yml`의
`${APP_OUTBOX_RELAY_ENABLED:false}`), `@ConditionalOnProperty`, `OutboxSettings`의 null 기본값이
모두 false로 같다.
- **store와 publisher가 있을 때만 켜진다.** 설정 전체는 `OutboxStorePort` 빈(persistence-jpa를 고르고
outbox를 켰을 때만 존재)을, 스케줄러는 추가로 `OutboxMessagePublishPort` 빈(messaging bridge가
제공)을 조건으로 건다. 두 auto-configuration 뒤에 오도록 `afterName`으로 순서를 명시한다. 발행할
곳이 없으면 스케줄러가 없으므로 PENDING 행이 그대로 남는다 — 예전에는
`DisabledMessagingSentinelAutoConfiguration`의 대역 publisher가 모든 claim을 실패시켜 DEAD로
소진했고, 그걸 막으려고 `OutboxRelayBrokerRequirementValidator`가 있었다. 둘 다 삭제했다.
messaging bridge의 `MessagingConfig`도 outbox 대역 publisher를 만들지 않는다. bridge가 있고
켜져 있는데 canonical `IntegrationEventPublishPort`가 없으면(producer id 없음) 기동을 거부한다.
- **왜 persistence-jpa가 아니라 여기인가.** 릴레이는 use case를 조립해 타이머로 구동하는 합성
코드다. driven adapter인 persistence-jpa가 use case를 만들거나 호출하면
`PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES` 규칙 위반이다. 모듈 타입은 하나도 이름으로
부르지 않고 포트만 쓰므로, persistence-jpa 한 줄을 지우면 릴레이도 함께 꺼진다.
- **`outboxLeaderElection` 토큰 빈은 outbox capability 안에서 조건 없이 등록한다.** SKIP LOCKED 는
멀티 인스턴스 전역 스위치와 무관하게 outbox relay 자체의 리더십/claim 메커니즘이라, outbox가 켜진
상태에서 별도 하위 토글로 끌 수 있게 만들지 않는다. 이 토큰은 outbox 조립의 자기 설명용 marker이지
`APP_MULTI_INSTANCE_ENABLED`의 전역 필수 빈이 아니다.
- **`outboxMetrics` 빈은 `MeterRegistry`가 없을 때 no-op 이다.** Actuator 가 클래스패스에 없는
환경에서도 와이어링이 깨지지 않도록 `ObjectProvider`로 레지스트리를 선택적으로 주입한다.
### OutboxLeaderElectionToken
- **로직이 전혀 없는 마커(documentation artifact) 빈이다.** 이 타입은 동작을 갖지 않고, Spring
컨텍스트에 존재한다는 사실만으로 멀티 인스턴스 조정 빈 요구사항을 충족시킨다.
- **리더 선출을 외부 코디네이터 없이 PostgreSQL `FOR UPDATE SKIP LOCKED`로 구현한다는 것을
표현한다.** claim 쿼리에 SKIP LOCKED 를 걸면 각 릴레이 인스턴스가 서로 겹치지 않는(disjoint) 행
집합을 가져가므로, 별도 코디네이터 없이도 "각 인스턴스가 자기 파티션의 리더" 형태로 리더 선출
의미가 성립한다.
### OutboxMetrics
- **`MeterRegistry`가 없으면 모든 메트릭 연산이 no-op 이다.** Actuator 가 없는 환경에서도 릴레이가
정상 동작해야 하므로, 생성자에서 `ObjectProvider`로 레지스트리를 조회해 없으면 게이지도 만들지
않고 기록도 건너뛴다.
- **카운터는 PUBLISHED/FAILED/DEAD 만 집계하고 IN_FLIGHT 는 제외한다.** IN_FLIGHT 는 릴레이 사이클의
종료 결과(terminal outcome)가 아니라 처리 중을 나타내는 일시적 상태라 카운터 outcome 으로 의미가
없다.
- **MultiGauge 갱신 시 `overwrite=true`로 등록한다.** 매 스케줄러 틱마다 store 를 다시 조회해
게이지를 갱신하는데, 이전 틱에 있었지만 지금은 사라진 event type 같은 오래된 time-series 태그를
덮어써 제거하기 위함이다.
### OutboxRelayScheduler
- **합성 루트가 직접 등록하고 컴포넌트 스캔하지 않는다.** 이 스케줄러가 구동하는 릴레이 use case 가
(위 OutboxRelayAutoConfiguration 사유로) 일부러 빈이 아니기 때문에, 그 use case 를 조립하는 `OutboxRelayAutoConfiguration`가
스케줄러 등록까지 같이 소유한다.
- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다.** 스케줄러
스레드가 죽으면 릴레이가 조용히 멈추므로, 다음 틱을 위해 스레드를 살려둔다. 단, 개별 발행 실패
(FAILED/DEAD 전이)는 relay가 persisted transition 성공 뒤 typed reporter로 canonical ERROR를
요청하고 결과에 반영하므로 이 catch 블록까지 오지 않는다 — 여기서 삼키는 것은 어디까지나
"예상치 못한" 예외다.
- **스케줄링은 `OutboxRelayAutoConfiguration`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC
idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지
않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다.
### OutboxSettings
- **튜닝 값(poll 주기·batch·timeout·보존)은 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를
추가하지 않는다는 결정에 따라, 값이 없으면 컴팩트 생성자에서 직접 기본값(예: `PT5S`, `20`,
`PT5M`, `PT10M`, `P7D`)을 채운다.
- **`reaper-interval`과 `published-retention`은 `adapter-persistence`의 `OutboxReaper`도 property
문자열로 읽는다.** 두 모듈이 같은 키를 공유하지만, 이 settings record 가 일곱 값 전체를 선언
하는 단일 지점(single place) 역할을 한다. strict 바인딩이라 prefix 아래 모르는 키는 기동 실패다. 기본값 yml(`ca-skeleton.outbox.*`)은 store를 가진
persistence-jpa 모듈이 `config/module-defaults/persistence-jpa.yml`로 가져온다.
+35
View File
@@ -0,0 +1,35 @@
plugins {
id 'ca.spring-library'
id 'ca.spring-config'
}
// The transactional outbox relay composition, selected by one line in a composition root:
//
// runtimeOnly project(':composition:outbox-relay')
//
// It builds the relay use case over the outbox store and the publish port and drives it on a
// timer, with its metrics. It names no module: the store (persistence-jpa, with
// ca-skeleton.outbox.enabled) and the publish port (the messaging bridge) are ports, and the relay
// assembles nothing until both exist. It lives here rather than in persistence-jpa because a
// driven adapter must not construct or call a use case.
//
// Not a composition root: it composes one capability and does not run. Same shape as
// :composition:notification-platform.
dependencies {
implementation project(':application-core')
// StrictSettingsBinder, the typed startup failures and the runtime warning fields.
implementation project(':adapter:outbound:support')
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework:spring-context'
implementation 'io.micrometer:micrometer-core'
implementation 'org.slf4j:slf4j-api'
// The relay's failure log writes its fields with StructuredArguments (see support's build.gradle:
// a module that logs structured fields declares the encoder itself).
implementation libs.logstash.logback.encoder
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.mockito:mockito-core'
testImplementation 'ch.qos.logback:logback-classic'
testRuntimeOnly 'org.yaml:snakeyaml'
}
@@ -0,0 +1,157 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=testCompileClasspath
ch.qos.logback:logback-classic:1.5.38=testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.38=testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
com.google.code.gson:gson:2.13.2=spotbugs
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.38.0=testCompileClasspath
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=testCompileClasspath,testRuntimeClasspath
jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
net.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.commons:commons-text:1.3=checkstyle
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
org.apache.logging.log4j:log4j-api:2.25.5=spotbugs,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.logging.log4j:log4j-to-slf4j:2.25.5=testCompileClasspath,testRuntimeClasspath
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath
org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.osgi:org.osgi.annotation.bundle:2.0.0=testCompileClasspath
org.osgi:org.osgi.annotation.versioning:1.1.2=testCompileClasspath
org.osgi:org.osgi.resource:1.0.0=testCompileClasspath
org.osgi:org.osgi.service.serviceloader:1.0.0=testCompileClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor
org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-logging:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-web:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath
org.yaml:snakeyaml:2.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath
empty=
@@ -0,0 +1,21 @@
package dev.caskeleton.composition.outbox;
/**
* Marker bean: presence in the context satisfies the multi-instance coordination requirement (no
* logic; SKIP LOCKED is the leadership mechanism). See README for the design rationale.
*/
public final class OutboxLeaderElectionToken {
private static final String STRATEGY_DESCRIPTION =
"SKIP LOCKED claim — each relay instance claims a disjoint row partition; "
+ "no external coordinator required (PostgreSQL FOR UPDATE SKIP LOCKED, I3/D8)";
public String strategyDescription() {
return STRATEGY_DESCRIPTION;
}
@Override
public String toString() {
return "OutboxLeaderElectionToken{strategy=SKIP_LOCKED}";
}
}
@@ -0,0 +1,118 @@
package dev.caskeleton.composition.outbox;
import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.OutboxRelayResult;
import dev.caskeleton.application.outbox.OutboxStorePort;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.MultiGauge;
import io.micrometer.core.instrument.Tags;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.ObjectProvider;
/**
* Outbox relay metric collector. No-op when no {@link MeterRegistry} is present (resolved via
* {@link ObjectProvider}). See README for the design rationale.
*/
public final class OutboxMetrics {
private static final String COUNTER_NAME = "outbox.publisher.published.total";
private static final String SIZE_GAUGE = "outbox.pending.size";
private static final String LAG_GAUGE = "outbox.publisher.lag";
private final OutboxStorePort store;
private final MeterRegistry registry; // null when no Actuator on classpath
private final MultiGauge pendingSizeGauge;
private final MultiGauge publisherLagGauge;
public OutboxMetrics(OutboxStorePort store, ObjectProvider<MeterRegistry> meterRegistryProvider) {
this.store = store;
this.registry = meterRegistryProvider.getIfAvailable();
if (this.registry != null) {
this.pendingSizeGauge =
MultiGauge.builder(SIZE_GAUGE)
.description("Number of outbox rows grouped by status")
.register(this.registry);
this.publisherLagGauge =
MultiGauge.builder(LAG_GAUGE)
.description("Age in seconds of the oldest unpublished row per event type")
.baseUnit("seconds")
.register(this.registry);
} else {
this.pendingSizeGauge = null;
this.publisherLagGauge = null;
}
}
/** Counts each per-event outcome (PUBLISHED, FAILED, DEAD, STALE; never IN_FLIGHT). */
public void recordRelayResult(OutboxRelayResult result) {
if (registry == null || result == null) {
return;
}
for (OutboxRelayResult.EventOutcome eo : result.outcomes()) {
try {
Counter.builder(COUNTER_NAME)
.tag("event_type", eo.eventType())
.tag("outcome", eo.outcome().name())
.register(registry)
.increment();
} catch (Exception ex) {
RuntimeWarnings.meterUnavailable(
"outbox",
COUNTER_NAME + "[eventType=" + eo.eventType() + ",outcome=" + eo.outcome() + "]",
ex);
}
}
}
/**
* Uses {@code overwrite=true} so stale time-series tags from removed event types are replaced
* rather than left dangling.
*
* @param now current wall-clock instant (for the lag gauge age computation)
*/
public void refresh(Instant now) {
if (registry == null) {
return;
}
refreshPendingSize();
refreshPublisherLag(now);
}
private void refreshPendingSize() {
try {
Map<OutboxEventStatus, Long> counts = store.countByStatus();
List<MultiGauge.Row<?>> rows = new ArrayList<>(OutboxEventStatus.values().length);
for (OutboxEventStatus status : OutboxEventStatus.values()) {
if (status == OutboxEventStatus.PUBLISHED) {
// The store does not count published rows (OutboxStorePort#countByStatus); a series
// pinned at 0 would read as "nothing published".
continue;
}
long count = counts.getOrDefault(status, 0L);
rows.add(MultiGauge.Row.of(Tags.of("status", status.name()), count));
}
pendingSizeGauge.register(rows, true);
} catch (Exception ex) {
RuntimeWarnings.meterUnavailable("outbox", "pending-size gauge", ex);
}
}
private void refreshPublisherLag(Instant now) {
try {
Map<String, Long> lagByType = store.oldestUnpublishedAgeSecondsByEventType(now);
List<MultiGauge.Row<?>> rows = new ArrayList<>(lagByType.size());
for (Map.Entry<String, Long> entry : lagByType.entrySet()) {
rows.add(MultiGauge.Row.of(Tags.of("event_type", entry.getKey()), entry.getValue()));
}
publisherLagGauge.register(rows, true);
} catch (Exception ex) {
RuntimeWarnings.meterUnavailable("outbox", "publisher-lag gauge", ex);
}
}
}
@@ -0,0 +1,108 @@
package dev.caskeleton.composition.outbox;
import dev.caskeleton.application.outbox.OutboxBackoffPolicy;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort;
import dev.caskeleton.application.outbox.OutboxStorePort;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import dev.caskeleton.application.transaction.TransactionPort;
import io.micrometer.core.instrument.MeterRegistry;
import java.time.Clock;
import java.util.SplittableRandom;
import java.util.UUID;
import java.util.random.RandomGenerator;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* The transactional outbox relay: assembles the relay use case manually and registers the leader
* election token, metrics, and scheduler.
*
* <p>Application composition: it wires application-core ports into a use case and drives it on a
* timer, which is why it is a composition module rather than part of the persistence module — a
* driven adapter must not construct or call use cases ({@code
* PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES}). It names no module type, only ports, and
* turns itself on from what the selected modules provide.
*
* <p>{@code ca-skeleton.outbox.enabled} is the capability switch; {@code relay-enabled} only
* decides whether the scheduler runs. The store port exists only while the persistence-jpa module
* is selected and its outbox is on, so this configuration waits for it: removing that module's
* build line removes the relay with it.
*
* <p>The scheduler additionally needs somewhere to publish. It is created only when an {@link
* OutboxMessagePublishPort} bean exists — the messaging bridge contributes one — so a deployment
* that selected no publishing capability keeps its PENDING rows instead of failing every claim
* against a stand-in and exhausting them to DEAD. Ordered after both contributing
* auto-configurations by name, because a bean condition only sees what was registered before it.
*/
@AutoConfiguration(
afterName = {
"dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration",
"dev.caskeleton.adapter.outbound.messaging.autoconfigure.MessagingBridgeRootAutoConfiguration"
})
@ConditionalOnProperty(prefix = "ca-skeleton.outbox", name = "enabled", havingValue = "true")
@ConditionalOnBean(OutboxStorePort.class)
// The relay is @Scheduled. It must switch scheduling on itself rather than rely on another
// capability (the PostgreSQL idempotency provider also does), or the relay runs only by accident.
@EnableScheduling
public class OutboxRelayAutoConfiguration {
/** Bound only once the capability is on, and strictly: see {@link OutboxSettings}. */
@Bean
public OutboxSettings outboxSettings(Environment environment) {
return OutboxSettings.bind(environment);
}
/** Relay use case is assembled manually here (not a bean) from {@link OutboxSettings} values. */
@Bean
@ConditionalOnProperty(name = "ca-skeleton.outbox.relay-enabled", havingValue = "true")
@ConditionalOnBean(OutboxMessagePublishPort.class)
public OutboxRelayScheduler outboxRelayScheduler(
OutboxStorePort store,
OutboxMessagePublishPort publishPort,
OutboxRelayFailureReportPort failureReporter,
TransactionPort tx,
Clock clock,
RandomGenerator outboxRandomGenerator,
OutboxSettings properties,
OutboxMetrics metrics) {
// One lease owner per relay instance. Its claims record it, and a completion applies only while
// this owner's lease still holds the row (V17 fencing).
PublishPendingOutboxEventsUseCase relayUseCase =
new PublishPendingOutboxEventsUseCase(
store,
publishPort,
failureReporter,
tx,
new OutboxBackoffPolicy(outboxRandomGenerator),
clock,
properties.batchSize(),
properties.inFlightTimeout(),
UUID.randomUUID().toString());
return new OutboxRelayScheduler(relayUseCase, metrics, clock);
}
/** Uses a {@code java.base} RNG so the relay also starts on the slim Temurin JRE image. */
@Bean
public RandomGenerator outboxRandomGenerator() {
return new SplittableRandom();
}
/** Registered unconditionally so the SKIP LOCKED leadership mechanism is always present. */
@Bean(name = "outboxLeaderElection")
public OutboxLeaderElectionToken outboxLeaderElection() {
return new OutboxLeaderElectionToken();
}
/** Outbox metrics collector; no-op when {@link MeterRegistry} is absent. */
@Bean
public OutboxMetrics outboxMetrics(
OutboxStorePort store, ObjectProvider<MeterRegistry> meterRegistryProvider) {
return new OutboxMetrics(store, meterRegistryProvider);
}
}
@@ -0,0 +1,61 @@
package dev.caskeleton.composition.outbox;
import static net.logstash.logback.argument.StructuredArguments.kv;
import dev.caskeleton.application.outbox.OutboxRelayResult;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import java.time.Clock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
/**
* Thin bootstrap scheduler that drives the outbox relay use case on a fixed-delay polling loop.
* Registered by {@code OutboxConfig}. See README for the design rationale.
*/
public class OutboxRelayScheduler {
private static final Logger log = LoggerFactory.getLogger(OutboxRelayScheduler.class);
private final PublishPendingOutboxEventsUseCase relayUseCase;
private final OutboxMetrics metrics;
private final Clock clock;
public OutboxRelayScheduler(
PublishPendingOutboxEventsUseCase relayUseCase, OutboxMetrics metrics, Clock clock) {
this.relayUseCase = relayUseCase;
this.metrics = metrics;
this.clock = clock;
}
/**
* Unexpected exceptions are caught (not propagated) so the scheduler thread stays alive for the
* next tick.
*/
@Scheduled(fixedDelayString = "${ca-skeleton.outbox.poll-interval:PT5S}")
public void relay() {
try {
OutboxRelayResult result = relayUseCase.handle(PublishPendingOutboxEventsCommand.INSTANCE);
if (result.claimedCount() > 0) {
log.debug(
"outbox relay cycle: claimed={} outcomes={}",
result.claimedCount(),
result.outcomes().size());
}
metrics.recordRelayResult(result);
metrics.refresh(clock.instant());
} catch (Exception ex) {
log.error(
"outbox relay scheduler: unexpected error in relay cycle — "
+ "relay will retry on the next tick",
kv("capability", "outbox"),
kv("operation", "relay"),
kv("retry.disposition", "next-tick"),
ex);
}
}
}
@@ -0,0 +1,74 @@
package dev.caskeleton.composition.outbox;
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import java.time.Duration;
import org.springframework.core.env.Environment;
/**
* The outbox capability's settings, bound strictly from {@code ca-skeleton.outbox.*}: every key
* under the prefix is one of these, so a misspelt one fails startup instead of leaving a default in
* force. The persistence module reads {@code enabled}, {@code reaper-interval} and {@code
* published-retention} too — the store and its reaper — but the keys are declared and validated
* once, here.
*
* @param enabled the capability switch; the relay composition only exists while it is true
* @param relayEnabled whether the relay scheduler runs; default {@code false}
* @param pollInterval how often the relay polls the outbox table; default {@code PT5S}
* @param batchSize maximum rows claimed per relay cycle; default {@code 20}
* @param inFlightTimeout in-flight orphan visibility window; default {@code PT5M}
* @param reaperInterval how often the reaper purges old PUBLISHED rows; default {@code PT10M}
* @param publishedRetention how long PUBLISHED rows are kept before the reaper deletes them;
* default {@code P7D}
*/
public record OutboxSettings(
Boolean enabled,
Boolean relayEnabled,
Duration pollInterval,
Integer batchSize,
Duration inFlightTimeout,
Duration reaperInterval,
Duration publishedRetention) {
static final String PREFIX = "ca-skeleton.outbox";
public OutboxSettings {
if (enabled == null) {
enabled = false;
}
if (relayEnabled == null) {
// Off unless asked for, like the module default and the scheduler condition: three sources
// answering "is the relay on" differently is how a missing key started it.
relayEnabled = false;
}
pollInterval = positive("poll-interval", pollInterval, Duration.ofSeconds(5));
if (batchSize == null) {
batchSize = 20;
} else if (batchSize <= 0) {
throw StartupFailures.envValidation(PREFIX + ".batch-size must be > 0, was " + batchSize);
}
inFlightTimeout = positive("in-flight-timeout", inFlightTimeout, Duration.ofMinutes(5));
reaperInterval = positive("reaper-interval", reaperInterval, Duration.ofMinutes(10));
publishedRetention = positive("published-retention", publishedRetention, Duration.ofDays(7));
}
/**
* Binds the prefix strictly.
*
* @param environment the environment to bind from
* @return the validated settings
*/
public static OutboxSettings bind(Environment environment) {
return StrictSettingsBinder.bind(environment, PREFIX, OutboxSettings.class);
}
private static Duration positive(String key, Duration value, Duration fallback) {
if (value == null) {
return fallback;
}
if (value.isZero() || value.isNegative()) {
throw StartupFailures.envValidation(PREFIX + "." + key + " must be positive, was " + value);
}
return value;
}
}
@@ -0,0 +1 @@
dev.caskeleton.composition.outbox.OutboxRelayAutoConfiguration
@@ -0,0 +1,131 @@
package dev.caskeleton.composition.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort;
import dev.caskeleton.application.outbox.OutboxStorePort;
import dev.caskeleton.application.transaction.TransactionPort;
import java.lang.reflect.Proxy;
import java.time.Clock;
import java.util.random.RandomGenerator;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.annotation.ImportCandidates;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.scheduling.config.TaskManagementConfigUtils;
class OutboxRelayAutoConfigurationTest {
@Test
void outboxRandomGeneratorIsAvailableInTheSlimJavaBaseRuntime() {
RandomGenerator random = new OutboxRelayAutoConfiguration().outboxRandomGenerator();
assertThat(random.getClass().getModule().getName()).isEqualTo("java.base");
}
@Test
void theModuleRegistersItsAutoConfiguration() {
assertThat(ImportCandidates.load(AutoConfiguration.class, getClass().getClassLoader()))
.contains(OutboxRelayAutoConfiguration.class.getName());
}
/**
* The settings used to be a scanned {@code @ConfigurationProperties} record, which ignores keys
* it does not declare: {@code batch-sise=500} ran with 20.
*/
@Test
void aMisspeltOutboxKeyFailsStartupInsteadOfLeavingTheDefaultInForce() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore)
.withPropertyValues("ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.batch-sise=500")
.run(
context ->
assertThat(context)
.getFailure()
.hasStackTraceContaining("ca-skeleton.outbox.batch-sise"));
}
@Test
void outboxCapabilityEnablesSchedulingWithIdempotencyDisabled() {
// given
ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore)
.withPropertyValues(
"ca-skeleton.outbox.enabled=true",
"ca-skeleton.outbox.relay-enabled=false",
"ca-skeleton.capabilities.idempotency.provider=disabled");
// when & then
runner.run(
context ->
assertThat(context)
.hasBean(TaskManagementConfigUtils.SCHEDULED_ANNOTATION_PROCESSOR_BEAN_NAME));
}
@Test
void theRelayRunsOnlyWhenSomethingCanPublishWhatItClaims() {
ApplicationContextRunner relayOn =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore)
.withBean(OutboxRelayFailureReportPort.class, () -> report -> {})
.withBean(TransactionPort.class, () -> mock(TransactionPort.class))
.withBean(Clock.class, Clock::systemUTC)
.withPropertyValues(
"ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.relay-enabled=true");
// No publish port: PENDING rows stay PENDING rather than being failed to DEAD.
relayOn.run(context -> assertThat(context).doesNotHaveBean(OutboxRelayScheduler.class));
relayOn
.withBean(OutboxMessagePublishPort.class, () -> mock(OutboxMessagePublishPort.class))
.run(context -> assertThat(context).hasSingleBean(OutboxRelayScheduler.class));
}
@Test
void withoutTheRelayKeyTheRelaySchedulerIsNotAssembled() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withBean(OutboxStorePort.class, OutboxRelayAutoConfigurationTest::unusedStore)
.withBean(OutboxRelayFailureReportPort.class, () -> report -> {})
.withBean(TransactionPort.class, () -> mock(TransactionPort.class))
.withBean(Clock.class, Clock::systemUTC)
.withBean(OutboxMessagePublishPort.class, () -> mock(OutboxMessagePublishPort.class))
.withPropertyValues("ca-skeleton.outbox.enabled=true")
.run(
context ->
assertThat(context)
.as("the module default says false; a missing key must mean the same thing")
.doesNotHaveBean(OutboxRelayScheduler.class));
}
@Test
void withoutTheRelationalStoreTheOutboxAssemblesNothing() {
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxRelayAutoConfiguration.class))
.withPropertyValues("ca-skeleton.outbox.enabled=true")
.run(context -> assertThat(context).doesNotHaveBean(OutboxMetrics.class));
}
private static OutboxStorePort unusedStore() {
return (OutboxStorePort)
Proxy.newProxyInstance(
OutboxStorePort.class.getClassLoader(),
new Class<?>[] {OutboxStorePort.class},
(proxy, method, arguments) -> {
if (method.getDeclaringClass() == Object.class) {
return switch (method.getName()) {
case "equals" -> proxy == arguments[0];
case "hashCode" -> System.identityHashCode(proxy);
default -> "unusedOutboxStore";
};
}
throw new AssertionError("store is not used while wiring: " + method.getName());
});
}
}
@@ -0,0 +1,76 @@
package dev.caskeleton.composition.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand;
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
import java.time.Clock;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
/** The relay's failure log carries bounded structured fields and no invented error code. */
class OutboxRelaySchedulerLoggingTest {
@Test
void outboxRelayUnexpectedFailureCarriesNextTickDispositionWithoutInventedErrorCode() {
PublishPendingOutboxEventsUseCase relay = mock(PublishPendingOutboxEventsUseCase.class);
OutboxMetrics metrics = mock(OutboxMetrics.class);
when(relay.handle(PublishPendingOutboxEventsCommand.INSTANCE))
.thenThrow(new IllegalStateException("unexpected"));
try (CapturedLogger captured = capture(OutboxRelayScheduler.class)) {
new OutboxRelayScheduler(relay, metrics, Clock.systemUTC()).relay();
ILoggingEvent event = captured.singleEvent();
assertThat(event.getLevel()).isEqualTo(Level.ERROR);
String arguments = renderedArguments(event);
assertThat(arguments)
.contains("capability=outbox")
.contains("operation=relay")
.contains("retry.disposition=next-tick")
.doesNotContain("error.code=");
assertThat(event.getThrowableProxy()).isNotNull();
}
}
private static CapturedLogger capture(Class<?> owner) {
Logger logger = (Logger) LoggerFactory.getLogger(owner);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.setContext((LoggerContext) LoggerFactory.getILoggerFactory());
appender.start();
logger.addAppender(appender);
return new CapturedLogger(logger, appender);
}
private static String renderedArguments(ILoggingEvent event) {
Object[] arguments = event.getArgumentArray();
if (arguments == null) {
return "";
}
return Arrays.stream(arguments).map(String::valueOf).collect(Collectors.joining(" | "));
}
private record CapturedLogger(Logger logger, ListAppender<ILoggingEvent> appender)
implements AutoCloseable {
ILoggingEvent singleEvent() {
assertThat(appender.list).hasSize(1);
return appender.list.get(0);
}
@Override
public void close() {
logger.detachAppender(appender);
appender.stop();
}
}
}
@@ -0,0 +1,102 @@
package dev.caskeleton.composition.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.time.Duration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.mock.env.MockEnvironment;
/** Binding and validation of {@link OutboxSettings} (feature-domain-event-outbox-contract I11). */
class OutboxSettingsTest {
@Test
void absentValuesTakeTheDocumentedDefaults() {
// when
OutboxSettings settings = new OutboxSettings(null, null, null, null, null, null, null);
// then
assertThat(settings)
.isEqualTo(
new OutboxSettings(
false,
false,
Duration.ofSeconds(5),
20,
Duration.ofMinutes(5),
Duration.ofMinutes(10),
Duration.ofDays(7)));
}
@Test
void kebabCaseKeysBindEveryField() {
// given
MockEnvironment environment =
new MockEnvironment()
.withProperty("ca-skeleton.outbox.enabled", "true")
.withProperty("ca-skeleton.outbox.relay-enabled", "true")
.withProperty("ca-skeleton.outbox.poll-interval", "10s")
.withProperty("ca-skeleton.outbox.batch-size", "50")
.withProperty("ca-skeleton.outbox.in-flight-timeout", "2m")
.withProperty("ca-skeleton.outbox.reaper-interval", "1h")
.withProperty("ca-skeleton.outbox.published-retention", "14d");
// when
OutboxSettings settings = OutboxSettings.bind(environment);
// then
assertThat(settings)
.isEqualTo(
new OutboxSettings(
true,
true,
Duration.ofSeconds(10),
50,
Duration.ofMinutes(2),
Duration.ofHours(1),
Duration.ofDays(14)));
}
@ParameterizedTest
@CsvSource({"0, batch-size must be > 0", "-1, batch-size must be > 0"})
void aNonPositiveBatchSizeIsRefused(int batchSize, String message) {
// when
Throwable thrown =
catchThrowable(() -> new OutboxSettings(true, true, null, batchSize, null, null, null));
// then
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("ca-skeleton.outbox." + message);
}
@ParameterizedTest
@CsvSource({
"PT0S, PT5M, PT10M, P7D, poll-interval must be positive",
"PT5S, PT0S, PT10M, P7D, in-flight-timeout must be positive",
"PT5S, PT5M, PT0S, P7D, reaper-interval must be positive",
"PT5S, PT5M, -PT1M, P7D, reaper-interval must be positive",
"PT5S, PT5M, PT10M, PT0S, published-retention must be positive",
"PT5S, PT5M, PT10M, -PT1H, published-retention must be positive"
})
void aNonPositiveDurationIsRefusedWithItsKey(
Duration poll, Duration inFlight, Duration reaper, Duration retention, String message) {
// when
Throwable thrown =
catchThrowable(
() -> new OutboxSettings(true, true, poll, null, inFlight, reaper, retention));
// then
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("ca-skeleton.outbox." + message);
}
}
+248
View File
@@ -0,0 +1,248 @@
# composition:service-runtime — 모든 서비스가 받는 runtime 배선
- Module ID: `composition-service-runtime`
- Gradle path: `:composition:service-runtime`
- Package: `dev.caskeleton.composition.runtime`
- 테스트: `./gradlew :composition:service-runtime:test --console=plain`
## 제공하는 것
capability와 무관하게 서비스 구성 루트 둘(app-bootstrap, sample-portfolio)이 모두 필요로 하는
runtime 배선이다. 예전에는 app-bootstrap에 있었고 sample이 그 복사본을 들고 있었다.
```
composition:service-runtime
├─ tracing/ TracingConfig(+ Tracer·SpanErrorRecorder·sampling gauge), TracingSettings,
│ TracingSampleRateResolver, TracingSamplingEnvironmentPostProcessor
├─ metrics/ MetricsContractConfig(cardinality deny-list + SLO 분포 filter)
├─ context/ DomainContextConfig
├─ logging/ PseudonymizationConfig, PrivacySettings (user_principal HMAC 가명화)
└─ management/security/ ManagementSecurityConfig (actuator chain)
```
- 모두 이 모듈의 `AutoConfiguration.imports`로 등록된다(sampling bridge는 `spring.factories`의
`EnvironmentPostProcessor`). 구성 루트의 component scan에 기대지 않는다.
- 설정 키는 옮기지 않았다: `ca-skeleton.tracing.*`, `ca-skeleton.privacy.*`. 값은 각 구성 루트의 `application.yml`/`config/observability.yml`에 있다.
- actuator chain은 servlet 웹 애플리케이션에서만 만들어지고, 구성 루트가 같은 이름
`actuatorSecurityFilterChain`의 bean을 두면 물러난다. sample-portfolio는 공개 데모라 그렇게
모든 요청을 허용하는 자기 chain을 둔다.
- sample 복사본과의 차이 중 원본을 따른 것: 샘플 레이트는 `RuntimeEnvironment` 어휘(prod 0.01,
그 밖 1.0)이고 `staging=0.10` 분기는 없다. 설정 검증 실패는 `IllegalStateException`이 아니라
`StartupFailures.envValidation`이다.
## 추가할 한 줄
```groovy
// app-bootstrap/build.gradle (sample-portfolio/build.gradle 도 같다)
runtimeOnly project(':composition:service-runtime')
```
기본 조립에 있다. 이 줄을 지우면 Tracer·SpanErrorRecorder·가명화 포트·DomainContextPropagator가
빠지고, 그것을 주입받는 web adapter(`RequestLoggingFilter`)와 persistence audit이 기동에 실패한다.
## 필요한 env 키
전체 목록과 타입은 `docs/registries/env-keys.yaml`이 SSOT다.
| 언제 | 키 |
| --- | --- |
| 프로덕션 전 | `APP_PRIVACY_PSEUDONYMIZATION_SALT` (비면 dev sentinel로 경고 후 기동) |
| 조정할 때 | `APP_TRACING_SAMPLE_RATE`, `OTEL_EXPORTER_OTLP_ENDPOINT` |
## 설계 결정 참조 (app-bootstrap에서 옮김)
이 모듈의 코드는 2026-09-28에 app-bootstrap(`autoconfigure/tracing`, `concurrency`, `metrics`,
`management/security`, `logging/PseudonymizationConfig`, `settings/PrivacySettings`)에서 옮겨 왔다.
아래 근거는 그때의 기록이다.
### tracing — 분산 트레이싱 wiring과 샘플링 정책
#### TracingConfig
- **컴포지션 루트에서 트레이싱을 조립한다.** 두 가지를 한다: (1) 시작 시 `tracing.sampling.rate`
게이지 등록, (2) `SpanErrorRecorder` 빈 등록.
- **`SpanErrorRecorder` 빈은 `@ConditionalOnBean(Tracer.class)`가 아니라 `ObjectProvider<Tracer>`로
런타임 존재 여부를 직접 조회한다.** 이유: `@ConditionalOnBean`은 사용자 정의 `@Configuration`에서
autoconfiguration 이 만드는 빈(여기서는 `Tracer`)을 조건으로 쓸 때 빈 등록 순서가 보장되지 않아
신뢰할 수 없기 때문이다. `Tracer`가 있으면 `MicrometerSpanErrorRecorder`를, 없으면
`SpanErrorRecorder.NOOP`을 반환한다.
- **`@ConditionalOnMissingBean(SpanErrorRecorder.class)`를 붙여, 테스트 mock 이나 fork 가 자체
`SpanErrorRecorder` 빈을 이미 등록한 경우 이 빈은 backoff 한다.** adapter-web 의
`GlobalExceptionHandler`는 `ObjectProvider`로 `SpanErrorRecorder`를 조회하므로, 자기 자신의 NOOP
self-default 에서 여기서 등록한 실제 구현으로 자동 교체된다.
- **OTel/Micrometer tracer 런타임은 이 repo 에서 seam 이 활성 상태다.** `micrometer-tracing-bridge-otel`
+ `opentelemetry-exporter-otlp`가 `app-bootstrap/build.gradle`에 실제로 wiring 되어 있다. 단, span
exporter 는 `OTEL_EXPORTER_OTLP_ENDPOINT`가 비어 있는 동안 꺼져 있고, 엔드포인트를 설정하면
export 가 시작된다.
- **게이지 등록 시 active profile 은 `Environment.getActiveProfiles()`의 첫 번째 값을 쓴다.** 멀티
프로파일 배포에서는 맨 앞에 나열된 프로파일이 권위 있는 배포 환경이라는 규약이다. `MeterRegistry`가
classpath 에 없으면(Actuator 미탑재) 게이지 등록은 조용히 no-op 이 된다.
- **`TracingSamplingRateGaugeRegistrar` record 는 등록된 active profile 과 resolved rate 를 노출하는
값 홀더다.** 정식 포트나 use case 가 아니라, 살아있는 `MeterRegistry` 없이도 테스트가 "무엇이
등록되었는지" 검사할 수 있게 하는 bootstrap 내부 전용 장치다.
#### TracingSettings
- **`ca-skeleton.tracing.*` 바인딩 `@ConfigurationProperties` record.** 세 env 키가 들어온다:
`APP_TRACING_ENABLED` → `enabled`, `APP_TRACING_SAMPLE_RATE` → `sampleRate`,
`OTEL_EXPORTER_OTLP_ENDPOINT` → `exporter.otlpEndpoint`.
- **`sampleRate`가 blank 이면 숫자 검증을 건너뛴다.** blank 는 "값이 잘못됐다"가 아니라 "프로파일별
기본값에 위임하라"는 신호이기 때문이다. 실제 런타임별 기본값(prod=0.01, dev/local=1.0)은 `TracingSampleRateResolver`가 적용하고,
profile vocabulary 자체는 `RuntimeEnvironment`가 소유한다. resolved 된 값은
`TracingSamplingEnvironmentPostProcessor`가 Spring Boot 네이티브
`management.tracing.sampling.probability`로 브리지한다.
- **검증은 시작 시 fail-fast 다.** `sampleRate`가 non-blank 인데 [0.0, 1.0] float 이 아니면 시작이
실패하고, `otlpEndpoint`가 non-empty 인데 scheme 없는 잘못된 URL 이면 시작이 실패한다. `enabled`는
Spring 바인딩이 `boolean` 타입을 강제하므로 추가 검증이 필요 없다. `otlpEndpoint`가 비어 있으면
exporter off 상태(seam 기본값)이고, 이것이 정상 동작이므로 검증을 통과시킨다.
- **`sampleRateValue()`는 호출 전 `sampleRate().isBlank()` 확인이 caller 규약이다.** blank 인 상태로
호출하면 `IllegalStateException`을 던지는데, 이는 파싱 오류가 아니라 caller 규약 위반을 드러내기
위한 것이다.
#### TracingSampleRateResolver
- **런타임별 트레이싱 샘플 정책을 적용한다.** prod=0.01(1%), dev/local=1.0(100%)이며,
런타임 이름의 SSOT는 `RuntimeEnvironment`다. shipped runtime이 아닌 값은 1.0 안전값을 사용한다. `APP_TRACING_SAMPLE_RATE`가 non-blank 이고 [0,1] float 로 파싱되면 프로파일 기본값을
override 한다.
- **Spring 의존성이 전혀 없는 순수 Java 로 작성했다.** 어떤 컨텍스트도 없이 단위 테스트할 수 있고,
`EnvironmentPostProcessor`(컨텍스트 생성 이전 단계)와 `TracingConfig`(빈 생성 단계) 양쪽에서 동일
로직을 재사용하기 위함이다.
#### TracingSamplingRateGauge
- **`tracing.sampling.rate` 게이지를 등록한다.** metric 계약: type=gauge, tag=`profile`(prod/dev/local
허용), value=resolved effective sample rate(double in [0.0, 1.0]).
- **deployable `RuntimeEnvironment`가 정확히 하나 해석될 때만 시리즈 하나를 방출한다.**
test/profileless/unknown 컨텍스트를 `local`로 가장하지 않으며, shipped app은 그보다 앞선 profile
validator에서 잘못된 런타임 환경을 거부한다.
- **`MeterRegistry`를 `ObjectProvider`로 조회하며, Actuator 미탑재로 빈이 없으면 등록을 조용히
건너뛴다.** 이는 `BackgroundJobMetrics` / `OutboxMetrics`의 선례를 그대로 따른다.
#### TracingSamplingEnvironmentPostProcessor
- **resolved 된 유효 샘플 비율을 Spring Boot 네이티브 키 `management.tracing.sampling.probability`로
단일화(브리지)하는 `EnvironmentPostProcessor`다.** 이를 통해 "프로파일별 기본값 + env override"라는
우리 규약을 Spring Boot 의 기본 샘플링 메커니즘에 그대로 연결한다.
- **브리지 우선순위.** (1) 사용자가 `management.tracing.sampling.probability`를 이미 명시했으면
덮어쓰지 않고 그대로 둔다, (2) `ca-skeleton.tracing.sample-rate`가 non-blank 면 그 값 사용, (3)
blank 면 `TracingSampleRateResolver.defaultRateForProfile(...)`로 active profile 기본값 적용.
- **`META-INF/spring.factories`에 `org.springframework.boot.EnvironmentPostProcessor` 키로 등록된다.**
`EnvironmentPostProcessor`는 ApplicationContext 가 생성되기 전에 실행되므로 일반 빈이 아니라
Spring Boot bootstrap factory 로 등록해야 한다.
#### MicrometerSpanErrorRecorder
- **NOOP 을 대체하는 Micrometer/OTel 기반 실제 `SpanErrorRecorder`다.** 현재 span 에 예외와
`error.code` 태그를 기록한다. 계약 이행: `Span.error(Throwable)` 호출(OTel bridge 를 통해
`recordException` + span status ERROR 매핑), `span.tag("error.code", errorCode)`(ca-tmpl 레지스트리
속성명), null `error`는 방어적 no-op, 현재 span 이 없으면 no-op.
- **"sampled span 에만 스택트레이스 부착" 정책은 의도적으로 구현하지 않았다.** Micrometer Tracing
추상화 레벨에서는 sampled 여부를 직접 제어할 수 없기 때문이다(`Span.isNoop()`은 OTel NOOP span
여부일 뿐 sampling 여부가 아니다). 다만 OTel SDK 의 unsampled span 은 이미 no-op 으로 처리되므로
명시적 sampled-only 분기가 없어도 실제 성능 부담은 없다.
---
### metrics — 메트릭 계약 MeterFilter 설치
#### MetricsCardinalityMeterFilter
- **금지 태그가 붙은 미터를 런타임에서 막는 방어 필터다.** 미터의 `Meter.Id`에 붙은 태그 키 중
하나라도 `ForbiddenMetricTags.FORBIDDEN`에 들어 있으면 그 미터를 `DENY`하고, 아니면 `NEUTRAL`을
반환한다. `user_id`, `request_id`, `raw_url`, `raw_query`, `raw_header_value`, `ip_address` 같은
고카디널리티(high-cardinality) 라벨 키는 고유 값마다 Prometheus 시계열을 하나씩 만들어 수백만
개로 폭증할 수 있어 차단한다.
- **이 필터는 카디널리티 계약의 런타임(runtime) 절반이다.** 정적(static) 절반은 레지스트리 계약
테스트(`MetricsAlertingContractTest`)가 담당한다 — 둘이 짝을 이뤄 심층 방어를 구성한다.
- **상태가 없어(stateless) 여러 레지스트리에 공유해도 안전하다.** public no-arg 생성자는
`MetricsContractConfig.install()`이 직접 인스턴스화하기 위한 계약이다.
#### MetricsContractConfig
- **`@PostConstruct`에서 `MeterFilter`들을 `MeterRegistry`에 직접 설치한다.** `@Bean MeterFilter`로
등록하지 않는 이유: 이 템플릿 클래스패스에는 `@Bean MeterFilter`를 자동 수집하는 Spring Boot
Actuator 자동설정(`MeterRegistryCustomizer`)이 없어서 `@Bean MeterFilter`는 그냥 동작하지 않는
(inert) 죽은 빈이 되기 때문이다. `OutboundHttpResilienceConfig`에서 확립한 선례를 따른다.
- **설치 순서가 중요하다.** (1) `MetricsCardinalityMeterFilter`(deny-list)를 먼저 설치해 금지 태그가
붙은 미터가 분포 필터에 닿기 전에 거부되도록 하고, (2) 그다음 `MetricsDistributionMeterFilter`
(SLO 기반 히스토그램 설정)를 설치한다.
- **필터는 설치 이후 등록되는 미터에만 적용된다.** `@PostConstruct`는 Spring 빈 생명주기 중 애플리
케이션 코드가 어떤 미터든 등록하기 전에 실행되므로 모든 미터가 필터 적용 대상이 된다.
- **`MeterRegistry` 부재 시 no-op.** `ObjectProvider.getIfAvailable()`로 해석해 레지스트리 빈이
없으면(Actuator 미탑재) DEBUG 로그만 남기고 설치를 건너뛴다.
- **`install(MeterRegistry)`를 public static 으로 둔 이유.** 계약 테스트가 Spring 컨텍스트 없이
`SimpleMeterRegistry`에 대해 직접 구동할 수 있게 하기 위함이다.
#### MetricsDistributionMeterFilter
- **소유한(owned) 타이머 메트릭 5종에만 SLO 기반 히스토그램·백분위 설정을 적용한다.** 대상:
`http.server.requests`, `http.server.requests.latency`, `dependency.client.requests`,
`db.query.duration`, `jvm.gc.pause`. 이들은 `metrics.yaml`에서 이 브랜치가 소유하고
`histogram_buckets: slo_driven`인 행이다. `resilience4j.circuitbreaker.calls`,
`hikaricp.connections.acquire`처럼 소비만 하고 소유하지 않는(consumed-but-not-owned) 행은 다른
브랜치 소유라 의도적으로 제외 — 덮어쓰면 안 된다.
- **히스토그램 전략은 두 축이다.**
- *인스턴스 간 집계 가능한 진실의 원천*: `percentilesHistogram(true)`(= `publishPercentileHistogram`)가
`_bucket` 시계열을 생성하고, Prometheus 에서 `histogram_quantile()`로 인스턴스 간 집계할 수 있다.
이것이 다중 인스턴스 배포의 정식 p50/p95/p99 다.
- *클라이언트 측 편의값(집계 불가)*: `percentiles(0.5, 0.9, 0.95, 0.99)`(= `publishPercentiles`)는
단일 인스턴스 가시성을 위한 사전 계산 분위 게이지를 제공한다. 이 값들은 인스턴스 간 평균을 내면
안 된다(통계적으로 틀림). 인스턴스 간 집계는 반드시 `histogram_quantile()`로 한다.
- **SLO 경계값 `100ms / 500ms / 1s / 5s`는 잠정 SLO 역산이며 외부 표준에서 유도한 값이 아니다.**
정식 SLO 가 채택되면 재검토 대상이다. 함께 설정하는 `minimumExpectedValue=1ms`,
`maximumExpectedValue=10s`는 히스토그램 버킷의 관측 범위를 한정한다.
- **상태가 없어 여러 레지스트리에 공유해도 안전하고,** public no-arg 생성자는
`MetricsContractConfig.install()`이 직접 인스턴스화하기 위한 계약이다.
---
### concurrency — 도메인 컨텍스트 전파 전략 조립
#### DomainContextConfig
- **`DomainContextPropagator`를 빈으로 노출하고 `ThreadLocalDomainContextPropagator`를 직접 만든다.**
제공하는 전략이 하나뿐이라 선택 설정(`strategy`)을 두지 않는다. 두 번째 전략이 생기면 그 구현과
둘 중 하나를 고르는 설정을 함께 추가한다(A-10c). use case 코드는 포트만 주입받으므로 어떤 전파
방식인지 모른다.
---
### logging — user_principal 가명화
#### PseudonymizationConfig
- **`user_principal`(로그에 남는 사용자 식별자)를 전체 HMAC 방식으로 가명화한다.**
`UserPrincipalPseudonymizerPort`(application-core)를 HMAC-SHA-256 구현(adapter-identifier)에
바인딩하고, 솔트는 `PrivacySettings`에서 가져온다. 원본 식별자를 그대로 로그에 남기지 않으려는
개인정보 보호 결정이다. 실제 사용처는 `adapter-web`의 `RequestLoggingFilter`로, 보안 principal 이
MDC/로그에 닿기 전에 이 포트로 가린다.
- **`@ConditionalOnMissingBean`으로 기본 구현을 둔다.** 이 템플릿을 포크한 프로젝트가 자기만의
가명화기(예: 향후 솔트 회전을 지원하는 구현)를 등록하면 이 기본 빈이 비켜주도록, 즉 기본값은
제공하되 교체를 막지 않도록 하기 위해서다.
#### PrivacySettings
- **보안/감사 로그에서 `user_principal`을 가명화하는 데 쓰는 HMAC salt 를 보관한다.**
`ca-skeleton.privacy.*` 바인딩(원천 `APP_PRIVACY_PSEUDONYMIZATION_SALT`). 알고리즘은 HMAC-SHA-256
+ 90일 회전 salt 이고, 이 salt 는 `secret`-tier 값이라 prod 에서는 반드시 secret manager 에서
공급되어야 한다.
- **검증은 `LoggingSettings`와 일관되게 "warn-and-default"다.** blank salt 는 경고를 남기고, 명확히
표시된 dev sentinel(`__LOCAL_DEV_` 접두사)로 폴백해 local/test 실행이 절대 기동에 실패하지 않게
한다.
- **이 sentinel 을 prod 로 승격하는 것은 별도 계약이 독립적으로
차단한다** — prod 프로파일에서 `__LOCAL_DEV_` 값이면 시작이 실패한다. 그 게이트는 이 record 의
책임 밖이라 여기서 중복 강제하지 않는다.
### management/security — 액추에이터 엔드포인트 보안 체인
#### ManagementSecurityConfig
- **`actuatorSecurityFilterChain`은 `@Order(0)`으로 메인 앱 체인(adapter-web `SecurityConfig`)보다
앞서 실행된다.** 그래서 액추에이터 엔드포인트에 매칭되는 요청은 앱 체인이 아니라 이 체인이
처리한다. 보안 매처는 `EndpointRequest.toAnyEndpoint()`로, 관리 포트의 `/actuator/**` 경로만 이
체인 범위에 든다.
- **접근 정책.** `health`, `info`, `prometheus`는 permit-all 이다. 자격 증명 없이 Kubernetes 프로브와
Prometheus 스크레이프가 접근할 수 있어야 하고, 이 엔드포인트들은 민감 데이터를 노출하지 않기
때문이다(health 상세는 `never`). 나머지(`/actuator` 링크 등)는 모두 인증이 필요하다.
- **`loggers`는 노출하지 않는다.** 이 체인에는 인증 수단(`httpBasic`·`oauth2ResourceServer`)이 없어
`authenticated()`에 걸리는 엔드포인트는 어떤 자격 증명으로도 도달할 수 없다. 그래서 `loggers`
노출과 `show-details: when-authorized`를 뺐다. 로그 레벨을 런타임에 보거나 바꿔야 하면 인증
수단을 이 체인에 먼저 붙이고 노출한다.
- **인증 실패 시 기본값 403 대신 401(자격 증명 필요)을 반환한다(`HttpStatusEntryPoint(UNAUTHORIZED)`).**
대화형 로그인이나 basic-auth realm 은 제공하지 않는다 — 관리 포트는 네트워크 ACL 뒤에 있으므로
올바른 HTTP 의미(credentials required)만 신호하면 된다.
- **운영에서 deny-by-default 보장은 관리 포트를 별도 포트로 분리해 네트워크 ACL 수준에서 강제한다.**
이 in-process 체인은 그 위의 심층 방어 계층이다.
- **SHAPE-OWNERSHIP(하드 규칙): 이 클래스는 `HealthEndpoint` / `HealthIndicator` / `HealthComponent`를
import·구현·의존해선 안 된다** — health 엔드포인트의 형태(shape)는 runtime-health 브랜치 소유다.
보안 매칭은 오직 엔드포인트 id 문자열로만 하고 health 내부 구조에는 절대 손대지 않는다. ArchUnit
규칙 `management_security_does_not_depend_on_health_internals`(`CleanArchitectureTest`)가 이를 정적
으로 강제한다.
@@ -0,0 +1,40 @@
plugins {
id 'ca.spring-library'
id 'ca.spring-config'
}
// The runtime wiring every service composition root needs, whatever its capabilities: distributed
// tracing, the metrics contract filters, domain-context propagation, user-principal
// pseudonymization and the actuator security chain. Selected by one line:
//
// runtimeOnly project(':composition:service-runtime')
//
// app-bootstrap and sample-portfolio take the same line. Before this module the sample carried a
// copy of each piece, and the copies had already drifted (a `staging` sampling rate the runtime
// vocabulary does not have, IllegalStateException where the original raised typed startup failures).
//
// Not a composition root: it assembles shared runtime infrastructure and does not run.
dependencies {
implementation project(':application-core')
implementation project(':shared-contract')
// Runtime profile snapshot, startup order, typed startup failures and runtime warnings.
implementation project(':adapter:outbound:support')
// support compiles against the structured-argument API only; a module that raises its startup
// failures or warnings ships the encoder (the same line outbox-relay carries).
implementation libs.logstash.logback.encoder
// The HMAC user-principal pseudonymizer behind UserPrincipalPseudonymizerPort.
implementation project(':adapter:outbound:identifier')
implementation 'org.springframework.boot:spring-boot-autoconfigure'
implementation 'org.springframework:spring-context'
// MeterRegistryCustomizer, EndpointRequest and the actuator types the chains match on.
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-core'
implementation 'io.micrometer:micrometer-tracing-bridge-otel'
implementation 'io.opentelemetry:opentelemetry-sdk'
// The actuator security chain.
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.mockito:mockito-core'
}
@@ -0,0 +1,185 @@
# This is a Gradle generated file for dependency locking.
# Manual edits can break the build and are not advised.
# This file is expected to be part of source control.
aopalliance:aopalliance:1.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
biz.aQute.bnd:biz.aQute.bnd.annotation:7.1.0=compileClasspath,testCompileClasspath
ch.qos.logback:logback-classic:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
ch.qos.logback:logback-core:1.5.38=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-annotations:2.21=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-core:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson.core:jackson-databind:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.fasterxml.jackson:jackson-bom:2.21.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,testAnnotationProcessor
com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,testAnnotationProcessor
com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs
com.github.spotbugs:spotbugs:4.10.2=spotbugs
com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs
com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,testAnnotationProcessor
com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,testAnnotationProcessor
com.google.auto:auto-common:1.2.2=annotationProcessor,testAnnotationProcessor
com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs
com.google.code.gson:gson:2.13.2=spotbugs
com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_annotations:2.38.0=compileClasspath,testCompileClasspath
com.google.errorprone:error_prone_annotations:2.41.0=spotbugs
com.google.errorprone:error_prone_annotations:2.47.0=checkstyle
com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,testAnnotationProcessor
com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,testAnnotationProcessor
com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.guava:guava:33.5.0-jre=annotationProcessor,testAnnotationProcessor
com.google.guava:guava:33.6.0-jre=checkstyle
com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,testAnnotationProcessor
com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,testAnnotationProcessor
com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins
com.jayway.jsonpath:json-path:2.10.0=testCompileClasspath,testRuntimeClasspath
com.puppycrawl.tools:checkstyle:13.5.0=checkstyle
com.vaadin.external.google:android-json:0.0.20131108.vaadin1=testCompileClasspath,testRuntimeClasspath
commons-beanutils:commons-beanutils:1.11.0=checkstyle
commons-collections:commons-collections:3.2.2=checkstyle
commons-io:commons-io:2.21.0=spotbugs
commons-logging:commons-logging:1.3.6=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
info.picocli:picocli:4.7.7=checkstyle
io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,testAnnotationProcessor
io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,testAnnotationProcessor
io.micrometer:context-propagation:1.2.1=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-commons:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-core:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-jakarta9:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-observation:1.16.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-tracing-bridge-otel:1.6.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.micrometer:micrometer-tracing:1.6.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry.semconv:opentelemetry-semconv:1.37.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-api:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-context:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-extension-trace-propagators:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-common:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-logs:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-metrics:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk-trace:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
io.opentelemetry:opentelemetry-sdk:1.55.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.activation:jakarta.activation-api:2.1.4=testCompileClasspath,testRuntimeClasspath
jakarta.annotation:jakarta.annotation-api:3.0.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
jakarta.xml.bind:jakarta.xml.bind-api:4.0.5=testCompileClasspath,testRuntimeClasspath
javax.inject:javax.inject:1=annotationProcessor,testAnnotationProcessor
jaxen:jaxen:2.0.6=spotbugs
net.bytebuddy:byte-buddy-agent:1.17.8=testCompileClasspath,testRuntimeClasspath
net.bytebuddy:byte-buddy:1.17.8=testCompileClasspath,testRuntimeClasspath
net.logstash.logback:logstash-logback-encoder:8.0=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
net.minidev:accessors-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.minidev:json-smart:2.6.0=testCompileClasspath,testRuntimeClasspath
net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs
org.antlr:antlr4-runtime:4.13.2=checkstyle
org.apache.bcel:bcel:6.12.0=spotbugs
org.apache.commons:commons-lang3:3.20.0=checkstyle,spotbugs
org.apache.commons:commons-text:1.15.0=spotbugs
org.apache.commons:commons-text:1.3=checkstyle
org.apache.httpcomponents:httpclient:4.5.13=checkstyle
org.apache.httpcomponents:httpcore:4.4.16=checkstyle
org.apache.logging.log4j:log4j-api:2.25.5=compileClasspath,runtimeClasspath,spotbugs,testCompileClasspath,testRuntimeClasspath
org.apache.logging.log4j:log4j-core:2.25.5=spotbugs
org.apache.logging.log4j:log4j-to-slf4j:2.25.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.apache.maven.doxia:doxia-core:1.12.0=checkstyle
org.apache.maven.doxia:doxia-logging-api:1.12.0=checkstyle
org.apache.maven.doxia:doxia-module-xdoc:1.12.0=checkstyle
org.apache.maven.doxia:doxia-sink-api:1.12.0=checkstyle
org.apache.tomcat.embed:tomcat-embed-core:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-el:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.tomcat.embed:tomcat-embed-websocket:11.0.24=testCompileClasspath,testRuntimeClasspath
org.apache.xbean:xbean-reflect:3.7=checkstyle
org.apiguardian:apiguardian-api:1.1.2=testCompileClasspath
org.assertj:assertj-core:3.27.7=testCompileClasspath,testRuntimeClasspath
org.awaitility:awaitility:4.3.0=testCompileClasspath,testRuntimeClasspath
org.codehaus.plexus:plexus-classworlds:2.6.0=checkstyle
org.codehaus.plexus:plexus-component-annotations:2.1.0=checkstyle
org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle
org.codehaus.plexus:plexus-utils:3.3.0=checkstyle
org.dom4j:dom4j:2.2.0=spotbugs
org.hamcrest:hamcrest:3.0=testCompileClasspath,testRuntimeClasspath
org.hdrhistogram:HdrHistogram:2.2.2=runtimeClasspath,testRuntimeClasspath
org.javassist:javassist:3.28.0-GA=checkstyle
org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,compileClasspath,runtimeClasspath,testAnnotationProcessor,testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-api:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter-engine:6.0.3=testRuntimeClasspath
org.junit.jupiter:junit-jupiter-params:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.jupiter:junit-jupiter:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-commons:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit.platform:junit-platform-engine:6.0.3=testRuntimeClasspath
org.junit.platform:junit-platform-launcher:6.0.3=testRuntimeClasspath
org.junit:junit-bom:6.0.3=testCompileClasspath,testRuntimeClasspath
org.junit:junit-bom:6.1.0=spotbugs
org.latencyutils:LatencyUtils:2.0.3=runtimeClasspath,testRuntimeClasspath
org.mockito:mockito-core:5.20.0=mockitoAgent,testCompileClasspath,testRuntimeClasspath
org.mockito:mockito-junit-jupiter:5.20.0=testCompileClasspath,testRuntimeClasspath
org.objenesis:objenesis:3.3=testRuntimeClasspath
org.opentest4j:opentest4j:1.3.0=testCompileClasspath,testRuntimeClasspath
org.osgi:org.osgi.annotation.bundle:2.0.0=compileClasspath,testCompileClasspath
org.osgi:org.osgi.annotation.versioning:1.1.2=compileClasspath,testCompileClasspath
org.osgi:org.osgi.resource:1.0.0=compileClasspath,testCompileClasspath
org.osgi:org.osgi.service.serviceloader:1.0.0=compileClasspath,testCompileClasspath
org.ow2.asm:asm-analysis:9.10.1=spotbugs
org.ow2.asm:asm-commons:9.10.1=spotbugs
org.ow2.asm:asm-tree:9.10.1=spotbugs
org.ow2.asm:asm-util:9.10.1=spotbugs
org.ow2.asm:asm:9.10.1=spotbugs
org.ow2.asm:asm:9.7.1=testCompileClasspath,testRuntimeClasspath
org.pcollections:pcollections:4.0.1=annotationProcessor,testAnnotationProcessor
org.reflections:reflections:0.10.2=checkstyle
org.skyscreamer:jsonassert:1.5.3=testCompileClasspath,testRuntimeClasspath
org.slf4j:jul-to-slf4j:2.0.18=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-api:2.0.18=compileClasspath,runtimeClasspath,spotbugs,spotbugsSlf4j,testCompileClasspath,testRuntimeClasspath
org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j
org.slf4j:slf4j-simple:2.0.18=checkstyle
org.springframework.boot:spring-boot-actuator-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-actuator:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-autoconfigure:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-configuration-processor:4.0.8=annotationProcessor
org.springframework.boot:spring-boot-health:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-http-converter:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-micrometer-metrics:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-micrometer-observation:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-resttestclient:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-security:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-servlet:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-actuator:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-jackson:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-logging:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-micrometer-metrics:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-security:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat-runtime:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-starter:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test-autoconfigure:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-tomcat:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-web-server:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc-test:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot-webmvc:4.0.8=testCompileClasspath,testRuntimeClasspath
org.springframework.boot:spring-boot:4.0.8=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.security:spring-security-config:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.security:spring-security-core:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.security:spring-security-crypto:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework.security:spring-security-web:7.0.7=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-aop:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-beans:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-context:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-core:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-expression:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-test:7.0.9=testCompileClasspath,testRuntimeClasspath
org.springframework:spring-web:7.0.9=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
org.springframework:spring-webmvc:7.0.9=testCompileClasspath,testRuntimeClasspath
org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs
org.xmlunit:xmlunit-core:2.10.4=testCompileClasspath,testRuntimeClasspath
org.yaml:snakeyaml:2.5=compileClasspath,runtimeClasspath,testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-core:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson.core:jackson-databind:3.1.5=testCompileClasspath,testRuntimeClasspath
tools.jackson:jackson-bom:3.1.5=testCompileClasspath,testRuntimeClasspath
empty=
@@ -0,0 +1,20 @@
package dev.caskeleton.composition.runtime.context;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
/**
* Wires the {@link DomainContextPropagator} bean. {@link ThreadLocalDomainContextPropagator} is the
* only shipped strategy, so there is no selection setting; a second strategy adds its own
* implementation and the setting that chooses between them at the same time.
*/
@AutoConfiguration
public class DomainContextConfig {
@Bean
public DomainContextPropagator domainContextPropagator() {
return new ThreadLocalDomainContextPropagator();
}
}
@@ -0,0 +1,33 @@
package dev.caskeleton.composition.runtime.logging;
import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings;
import java.nio.charset.StandardCharsets;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Privacy settings bound from {@code ca-skeleton.privacy.*}. Holds the HMAC salt used to
* pseudonymize {@code user_principal} in security/audit logs. A blank salt is "warn-and-default":
* it logs a warning and falls back to a dev sentinel so local/test runs never fail to start. See
* README for the design rationale.
*/
@ConfigurationProperties(prefix = "ca-skeleton.privacy")
public record PrivacySettings(String pseudonymizationSalt) {
/** Dev/local fallback salt — the {@code __LOCAL_DEV_} prefix is the prod-unsafe sentinel. */
static final String DEV_SENTINEL_SALT = "__LOCAL_DEV_pseudonymization_salt";
public PrivacySettings {
if (pseudonymizationSalt == null || pseudonymizationSalt.isBlank()) {
RuntimeWarnings.settingFallback(
"APP_PRIVACY_PSEUDONYMIZATION_SALT",
pseudonymizationSalt,
"a dev sentinel salt",
"it is blank; set a real secret-manager value before production");
pseudonymizationSalt = DEV_SENTINEL_SALT;
}
}
public byte[] saltBytes() {
return pseudonymizationSalt.getBytes(StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,24 @@
package dev.caskeleton.composition.runtime.logging;
import dev.caskeleton.adapter.outbound.identifier.HmacUserPrincipalPseudonymizer;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* Composition-root wiring for {@code user_principal} pseudonymization.
* {@code @ConditionalOnMissingBean} lets a forking project substitute its own pseudonymizer. See
* README for the design rationale.
*/
@AutoConfiguration
@EnableConfigurationProperties(PrivacySettings.class)
public class PseudonymizationConfig {
@Bean
@ConditionalOnMissingBean
UserPrincipalPseudonymizerPort userPrincipalPseudonymizer(PrivacySettings privacySettings) {
return new HmacUserPrincipalPseudonymizer(privacySettings.saltBytes());
}
}
@@ -0,0 +1,67 @@
package dev.caskeleton.composition.runtime.management.security;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest;
import org.springframework.boot.security.autoconfigure.actuate.web.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.security.autoconfigure.web.servlet.ServletWebSecurityAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
/**
* Actuator endpoint security chain, ordered ahead of the main app chain. Security matching is done
* by endpoint id string only, never by health endpoint internals. See README for the design
* rationale.
*
* <p>Ordered before Boot's own web-security auto-configurations: a {@link SecurityFilterChain} bean
* is what makes their default chains back off, exactly as it did when this class was a scanned
* configuration of app-bootstrap. It needs {@link HttpSecurity} to exist by then, which means the
* composition has enabled web security itself — the web adapter's {@code SecurityConfig} does, from
* its highest-precedence auto-configuration. A context without it (a narrow slice that switched web
* security off) gets no chain from here rather than a startup failure, and one that leaves web
* security entirely to Boot gets Boot's actuator default (health open, everything else
* authenticated).
*
* <p>A composition root that deliberately wants another actuator posture declares its own bean
* named {@code actuatorSecurityFilterChain}; this one then steps aside instead of putting two
* chains with the same matcher in front of the same requests. The standalone sample does that.
*/
@AutoConfiguration(
before = {
ServletWebSecurityAutoConfiguration.class,
ManagementWebSecurityAutoConfiguration.class
})
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({HttpSecurity.class, EndpointRequest.class})
@ConditionalOnBean(HttpSecurity.class)
public class ManagementSecurityConfig {
@Bean
@Order(0)
@ConditionalOnMissingBean(name = "actuatorSecurityFilterChain")
public SecurityFilterChain actuatorSecurityFilterChain(HttpSecurity http) throws Exception {
http.securityMatcher(EndpointRequest.toAnyEndpoint())
.csrf(csrf -> csrf.disable())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// Answer 401 (credentials required) instead of the default 403; no interactive login.
.exceptionHandling(
ex -> ex.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
.authorizeHttpRequests(
auth ->
auth
// permit-all for probes and Prometheus scrape.
.requestMatchers(EndpointRequest.to("health", "info", "prometheus"))
.permitAll()
.anyRequest()
.authenticated());
return http.build();
}
}
@@ -0,0 +1,31 @@
package dev.caskeleton.composition.runtime.metrics;
import dev.caskeleton.shared.metrics.ForbiddenMetricTags;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;
/**
* {@link MeterFilter} that blocks high-cardinality label keys at runtime. See README for the design
* rationale.
*
* @see ForbiddenMetricTags
* @see MetricsContractConfig
*/
public final class MetricsCardinalityMeterFilter implements MeterFilter {
public MetricsCardinalityMeterFilter() {
// public no-arg constructor — required by MetricsContractConfig.install()
}
@Override
public MeterFilterReply accept(Meter.Id id) {
for (Tag tag : id.getTags()) {
if (ForbiddenMetricTags.isForbidden(tag.getKey())) {
return MeterFilterReply.DENY;
}
}
return MeterFilterReply.NEUTRAL;
}
}
@@ -0,0 +1,52 @@
package dev.caskeleton.composition.runtime.metrics;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/**
* Installs the metrics MeterFilters onto the MeterRegistry (deny-list before histogram config). See
* README for the design rationale.
*
* <p>A {@link MeterRegistryCustomizer} rather than a {@code @PostConstruct} that fetched the
* registry and configured it. Micrometer applies a filter only to meters registered after it, and
* by the time a {@code @PostConstruct} ran, beans constructed earlier had already registered theirs
* — so Micrometer warned, and the warning was the visible half of the real problem: the cardinality
* and distribution policies were being applied to some meters and not others. A customizer runs
* while Boot is building the registry, before any meter exists.
*
* @see MetricsCardinalityMeterFilter
* @see MetricsDistributionMeterFilter
*/
@AutoConfiguration
public class MetricsContractConfig {
/**
* Applies both filters at registry construction.
*
* <p>Ordered first because a deny-list that runs after a histogram configuration has already
* accepted a meter is a deny-list with a hole in it.
*
* @return the customizer Boot applies to every registry it creates
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public MeterRegistryCustomizer<MeterRegistry> metricsContractMeterFilters() {
return MetricsContractConfig::install;
}
/**
* Public and static so contract tests can drive it directly against a {@link
* io.micrometer.core.instrument.simple.SimpleMeterRegistry} without a Spring context. See README
* for the design rationale.
*
* @param registry the registry to configure; must not be {@code null}
*/
public static void install(MeterRegistry registry) {
registry.config().meterFilter(new MetricsCardinalityMeterFilter());
registry.config().meterFilter(new MetricsDistributionMeterFilter());
}
}
@@ -0,0 +1,48 @@
package dev.caskeleton.composition.runtime.metrics;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import java.time.Duration;
import java.util.Set;
/**
* {@link MeterFilter} that applies SLO-driven histogram and percentile configuration to a fixed set
* of owned timer metrics. See README for the design rationale.
*
* @see MetricsContractConfig
* @see MetricsCardinalityMeterFilter
*/
public final class MetricsDistributionMeterFilter 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");
public MetricsDistributionMeterFilter() {
// public no-arg constructor — required by MetricsContractConfig.install()
}
@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,30 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
/** Micrometer/OTel-backed {@link SpanErrorRecorder}. See README for the design rationale. */
public final class MicrometerSpanErrorRecorder implements SpanErrorRecorder {
private final Tracer tracer;
public MicrometerSpanErrorRecorder(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);
}
}
}
@@ -0,0 +1,102 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.tracing.Tracer;
import io.micrometer.tracing.otel.bridge.OtelBaggageManager;
import io.micrometer.tracing.otel.bridge.OtelCurrentTraceContext;
import io.micrometer.tracing.otel.bridge.OtelTracer;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.samplers.Sampler;
import java.util.List;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/** Composition-root wiring for distributed tracing. See README for the design rationale. */
@AutoConfiguration
@EnableConfigurationProperties(TracingSettings.class)
public class TracingConfig {
private final TracingSettings properties;
private final Environment environment;
private final ObjectProvider<MeterRegistry> meterRegistryProvider;
// ObjectProvider<MeterRegistry> so wiring works even when no MeterRegistry bean exists.
public TracingConfig(
TracingSettings properties,
Environment environment,
ObjectProvider<MeterRegistry> meterRegistryProvider) {
this.properties = properties;
this.environment = environment;
this.meterRegistryProvider = meterRegistryProvider;
}
@Bean
public TracingSamplingRateGaugeRegistrar tracingSamplingRateGaugeRegistrar() {
RuntimeProfileSnapshot profiles = RuntimeProfileSnapshot.from(environment);
List<String> activeProfiles = profiles.activeProfiles();
double effectiveRate =
new TracingSampleRateResolver().resolve(activeProfiles, properties.sampleRate());
var runtimeEnvironment = profiles.resolve();
runtimeEnvironment.ifPresent(
runtime ->
TracingSamplingRateGauge.register(
runtime.profileName(), effectiveRate, meterRegistryProvider));
return new TracingSamplingRateGaugeRegistrar(
runtimeEnvironment.map(RuntimeEnvironment::profileName).orElse("unresolved"),
effectiveRate);
}
@Bean
@ConditionalOnMissingBean(Tracer.class)
@ConditionalOnProperty(
prefix = "ca-skeleton.tracing",
name = "enabled",
havingValue = "true",
matchIfMissing = true)
Tracer micrometerTracer() {
double sampleRate =
new TracingSampleRateResolver()
.resolve(
RuntimeProfileSnapshot.from(environment).activeProfiles(), properties.sampleRate());
SdkTracerProvider tracerProvider =
SdkTracerProvider.builder()
.setSampler(Sampler.parentBased(Sampler.traceIdRatioBased(sampleRate)))
.build();
OpenTelemetrySdk openTelemetry =
OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).build();
OtelCurrentTraceContext currentTraceContext = new OtelCurrentTraceContext();
return new OtelTracer(
openTelemetry.getTracer("dev.caskeleton"),
currentTraceContext,
event -> {},
new OtelBaggageManager(currentTraceContext, List.of(), List.of()));
}
/**
* {@link ObjectProvider}, not {@code @ConditionalOnBean(Tracer.class)}: a missing {@link Tracer}
* yields {@link SpanErrorRecorder#NOOP} rather than no bean, so downstream injection points never
* break when tracing is off.
*/
@Bean
@ConditionalOnMissingBean(SpanErrorRecorder.class)
SpanErrorRecorder micrometerSpanErrorRecorder(ObjectProvider<Tracer> tracerProvider) {
Tracer tracer = tracerProvider.getIfAvailable();
if (tracer == null) {
return SpanErrorRecorder.NOOP;
}
return new MicrometerSpanErrorRecorder(tracer);
}
/** Exists so tests can inspect what was registered without a live MeterRegistry. */
public record TracingSamplingRateGaugeRegistrar(
String activeProfile, double effectiveSampleRate) {}
}
@@ -0,0 +1,58 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
import java.util.Collection;
/** Resolves the effective tracing sample rate from the canonical runtime environment. */
public final class TracingSampleRateResolver {
private static final double PRODUCTION_DEFAULT = 0.01d;
private static final double NON_PRODUCTION_DEFAULT = 1.0d;
/**
* Resolves a configured override, otherwise the default for the canonical runtime environment.
*/
public double resolve(Collection<String> activeProfiles, String configuredRate) {
if (configuredRate != null && !configuredRate.isBlank()) {
try {
double parsed = Double.parseDouble(configuredRate.trim());
if (parsed >= 0.0d && parsed <= 1.0d) {
return parsed;
}
} catch (NumberFormatException ignored) {
// Invalid configured values are rejected by TracingSettings during normal boot. Keeping the
// resolver defensive preserves the existing pure-function contract for direct callers.
}
}
return defaultRateForProfiles(activeProfiles);
}
/** Backward-compatible single-profile entry used by focused unit tests and simple callers. */
public double resolve(String activeProfile, String configuredRate) {
return resolve(
activeProfile == null ? java.util.List.of() : java.util.List.of(activeProfile),
configuredRate);
}
/** Default for the currently active shipped runtime environment. */
public static double defaultRateForProfiles(Collection<String> activeProfiles) {
return RuntimeEnvironment.resolve(activeProfiles)
.map(TracingSampleRateResolver::defaultRateForEnvironment)
.orElse(NON_PRODUCTION_DEFAULT);
}
/**
* Backward-compatible single-profile helper. Unknown/test/profileless values are non-production.
*/
public static double defaultRateForProfile(String profile) {
return defaultRateForProfiles(
profile == null ? java.util.List.of() : java.util.List.of(profile));
}
private static double defaultRateForEnvironment(RuntimeEnvironment environment) {
return switch (environment) {
case PROD -> PRODUCTION_DEFAULT;
case LOCAL, DEV -> NON_PRODUCTION_DEFAULT;
};
}
}
@@ -0,0 +1,49 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import dev.caskeleton.adapter.outbound.support.startup.StartupOrder;
import java.util.List;
import java.util.Map;
import org.springframework.boot.EnvironmentPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
/**
* Bridges the resolved tracing sample rate into Spring Boot's native {@code
* management.tracing.sampling.probability}. Registered via {@code META-INF/spring.factories}. See
* README for the design rationale.
*/
public class TracingSamplingEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
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 TracingSampleRateResolver resolver = new TracingSampleRateResolver();
@Override
public void postProcessEnvironment(
ConfigurableEnvironment environment, SpringApplication application) {
// A user-supplied value takes precedence.
if (environment.containsProperty(NATIVE_KEY)) {
return;
}
List<String> activeProfiles = RuntimeProfileSnapshot.from(environment).activeProfiles();
String configured = environment.getProperty(CA_SAMPLE_RATE_KEY);
double rate = resolver.resolve(activeProfiles, configured);
environment
.getPropertySources()
.addLast(
new MapPropertySource(
"tracingSamplingBridge", Map.of(NATIVE_KEY, String.valueOf(rate))));
}
@Override
public int getOrder() {
// Declared rather than inherited. Implementing EnvironmentPostProcessor without Ordered means
// LOWEST_PRECEDENCE by default, which is the same value three other post-processors returned
// explicitly — four things claiming the same position, none of them saying so (BOOT-005).
return StartupOrder.TRACING_SAMPLING;
}
}
@@ -0,0 +1,38 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.adapter.outbound.support.startup.RuntimeWarnings;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.ObjectProvider;
/**
* Registers the {@code tracing.sampling.rate} gauge. Resolves the registry via an {@link
* ObjectProvider} so it stays a no-op when no {@code MeterRegistry} bean is present. See README for
* the design rationale.
*/
public final class TracingSamplingRateGauge {
public static final String METRIC_NAME = "tracing.sampling.rate";
public static final String TAG_PROFILE = "profile";
private TracingSamplingRateGauge() {}
public static void register(
String activeProfile,
double effectiveSampleRate,
ObjectProvider<MeterRegistry> meterRegistryProvider) {
MeterRegistry registry = meterRegistryProvider.getIfAvailable();
if (registry == null) {
return; // no-op: no Actuator / MeterRegistry on classpath
}
try {
Gauge.builder(METRIC_NAME, () -> effectiveSampleRate)
.tag(TAG_PROFILE, activeProfile != null ? activeProfile : "unknown")
.description("Effective distributed-tracing sample rate for the active profile")
.register(registry);
} catch (RuntimeException ex) {
RuntimeWarnings.meterUnavailable("tracing", METRIC_NAME, ex);
}
}
}
@@ -0,0 +1,100 @@
package dev.caskeleton.composition.runtime.tracing;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import java.net.URI;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
/**
* Tracing settings bound from {@code ca-skeleton.tracing.*}. A blank {@code sampleRate} means
* "defer to the per-profile default". See README for the design rationale.
*/
@ConfigurationProperties(prefix = "ca-skeleton.tracing")
@Validated
public record TracingSettings(boolean enabled, String sampleRate, Exporter exporter) {
/** Nested properties for the OTLP exporter endpoint. */
public record Exporter(String otlpEndpoint) {
public Exporter {
if (otlpEndpoint == null) {
otlpEndpoint = "";
}
}
public boolean isConfigured() {
return otlpEndpoint != null && !otlpEndpoint.isBlank();
}
}
public TracingSettings {
if (sampleRate == null) {
sampleRate = "";
}
if (exporter == null) {
exporter = new Exporter("");
}
// Blank sampleRate = defer to the per-profile default; skip numeric validation.
if (!sampleRate.isBlank()) {
validateSampleRate(sampleRate);
}
validateOtlpEndpoint(exporter.otlpEndpoint());
}
/**
* Precondition: {@link #sampleRate()} must be non-blank — blank means "defer to the per-profile
* default", so callers must check {@code sampleRate().isBlank()} first (throws {@link
* IllegalStateException} otherwise).
*/
public double sampleRateValue() {
if (sampleRate.isBlank()) {
throw new IllegalStateException(
"sampleRateValue() called on a blank sampleRate — blank means "
+ "\"defer to TracingSampleRateResolver per-profile default\". "
+ "Check sampleRate().isBlank() before calling this method.");
}
return Double.parseDouble(sampleRate.trim());
}
private static void validateSampleRate(String raw) {
try {
double v = Double.parseDouble(raw.trim());
if (v < 0.0 || v > 1.0) {
throw StartupFailures.envValidation(
"APP_TRACING_SAMPLE_RATE must be a float in [0.0, 1.0] "
+ "(feature-distributed-tracing-contract D6 float_between_0_and_1); "
+ "got: "
+ raw);
}
} catch (NumberFormatException ex) {
throw StartupFailures.envValidation(
"APP_TRACING_SAMPLE_RATE must be a float in [0.0, 1.0] "
+ "(feature-distributed-tracing-contract D6 float_between_0_and_1); "
+ "got: "
+ raw);
}
}
private static void validateOtlpEndpoint(String endpoint) {
if (endpoint == null || endpoint.isBlank()) {
return; // empty = exporter off
}
try {
URI uri = URI.create(endpoint.trim());
String scheme = uri.getScheme();
if (scheme == null || scheme.isBlank()) {
throw StartupFailures.envValidation(
"OTEL_EXPORTER_OTLP_ENDPOINT must be a valid URL with a scheme "
+ "(feature-distributed-tracing-contract D1 url_or_empty); "
+ "got: "
+ endpoint);
}
} catch (IllegalArgumentException ex) {
throw StartupFailures.envValidation(
"OTEL_EXPORTER_OTLP_ENDPOINT must be a valid URL or empty "
+ "(feature-distributed-tracing-contract D1 url_or_empty); "
+ "got: "
+ endpoint);
}
}
}
@@ -0,0 +1,2 @@
org.springframework.boot.EnvironmentPostProcessor=\
dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor
@@ -0,0 +1,5 @@
dev.caskeleton.composition.runtime.context.DomainContextConfig
dev.caskeleton.composition.runtime.logging.PseudonymizationConfig
dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig
dev.caskeleton.composition.runtime.metrics.MetricsContractConfig
dev.caskeleton.composition.runtime.tracing.TracingConfig
@@ -0,0 +1,94 @@
package dev.caskeleton.composition.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupOrder;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import dev.caskeleton.composition.runtime.context.DomainContextConfig;
import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig;
import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig;
import dev.caskeleton.composition.runtime.metrics.MetricsContractConfig;
import dev.caskeleton.composition.runtime.tracing.TracingConfig;
import dev.caskeleton.composition.runtime.tracing.TracingSamplingEnvironmentPostProcessor;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.annotation.ImportCandidates;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
class ServiceRuntimeRegistrationTest {
private static final List<Class<?>> ROOTS =
List.of(
DomainContextConfig.class,
PseudonymizationConfig.class,
ManagementSecurityConfig.class,
MetricsContractConfig.class,
TracingConfig.class);
@Test
void everyRootIsAnAutoConfigurationBootDiscoversFromThisModule() {
// given
ClassLoader loader = getClass().getClassLoader();
// when
List<String> candidates =
ImportCandidates.load(AutoConfiguration.class, loader).getCandidates();
// then
assertThat(candidates).containsAll(ROOTS.stream().map(Class::getName).toList());
assertThat(ROOTS).allMatch(root -> root.isAnnotationPresent(AutoConfiguration.class));
}
@Test
void theSamplingBridgeIsRegisteredAsAnEnvironmentPostProcessor() throws IOException {
// given
ClassPathResource factories = new ClassPathResource("META-INF/spring.factories");
// when
Properties registrations = PropertiesLoaderUtils.loadProperties(factories);
// then
assertThat(registrations.getProperty("org.springframework.boot.EnvironmentPostProcessor"))
.contains(TracingSamplingEnvironmentPostProcessor.class.getName());
}
@Test
void theSamplingBridgeTakesItsCentralStartupOrderPosition() {
// given
TracingSamplingEnvironmentPostProcessor bridge = new TracingSamplingEnvironmentPostProcessor();
// when
int order = bridge.getOrder();
// then
assertThat(order).isEqualTo(StartupOrder.TRACING_SAMPLING);
}
@Test
void aNonWebContextGetsTheRuntimeBeansWithoutAnActuatorChain() {
// given
ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ROOTS.toArray(Class<?>[]::new)))
.withPropertyValues("ca-skeleton.privacy.pseudonymization-salt=test-salt");
// when
runner.run(
context -> {
// then
assertThat(context).hasNotFailed();
assertThat(context).hasSingleBean(DomainContextPropagator.class);
assertThat(context).hasSingleBean(UserPrincipalPseudonymizerPort.class);
assertThat(context).hasSingleBean(SpanErrorRecorder.class);
assertThat(context).doesNotHaveBean("actuatorSecurityFilterChain");
});
}
}
@@ -0,0 +1,91 @@
package dev.caskeleton.composition.runtime.logging;
import static org.assertj.core.api.Assertions.assertThat;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Configuration;
class PrivacySettingsTest {
private static final String BLANK_SALT_WARNING =
"APP_PRIVACY_PSEUDONYMIZATION_SALT was rejected and its default applied";
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(EnableProperties.class);
// A ListAppender attached directly to the PrivacySettings logger records events synchronously on
// the thread that calls log.warn(). This is why it replaced CapturedOutput, which had this test
// quarantined: CapturedOutput reads a shared stream that the JVM-global async appender (installed
// on root by a sibling @SpringBootTest) flushes late, racing output.getOut(). A per-logger
// ListAppender is immune — the event lands before runner.run() returns.
private Logger privacyLogger;
private ListAppender<ILoggingEvent> logAppender;
@BeforeEach
void attachAppender() {
// The fallback warning is emitted through RuntimeWarnings, which owns one logger for
// every runtime warning in this leaf (BOOT-009) — so the appender attaches there, not to
// the settings record that used to hold its own.
privacyLogger = (Logger) LoggerFactory.getLogger("dev.caskeleton.bootstrap.runtime");
logAppender = new ListAppender<>();
logAppender.start();
privacyLogger.addAppender(logAppender);
}
@AfterEach
void detachAppender() {
privacyLogger.detachAppender(logAppender);
logAppender.stop();
}
@Test
void blankSaltWarnsAndFallsBackToDevSentinel() {
runner
.withPropertyValues("ca-skeleton.privacy.pseudonymization-salt=")
.run(
context -> {
assertThat(context).hasNotFailed();
PrivacySettings settings = context.getBean(PrivacySettings.class);
assertThat(settings.pseudonymizationSalt())
.isEqualTo(PrivacySettings.DEV_SENTINEL_SALT);
assertThat(logAppender.list)
.anySatisfy(
event -> {
assertThat(event.getLevel()).isEqualTo(Level.WARN);
assertThat(event.getFormattedMessage()).contains(BLANK_SALT_WARNING);
});
});
}
@Test
void realSaltIsUsedAndExposedAsUtf8Bytes() {
runner
.withPropertyValues("ca-skeleton.privacy.pseudonymization-salt=prod-salt-9f")
.run(
context -> {
assertThat(context).hasNotFailed();
PrivacySettings settings = context.getBean(PrivacySettings.class);
assertThat(settings.pseudonymizationSalt()).isEqualTo("prod-salt-9f");
assertThat(settings.saltBytes())
.isEqualTo("prod-salt-9f".getBytes(StandardCharsets.UTF_8));
assertThat(logAppender.list)
.noneSatisfy(
event ->
assertThat(event.getFormattedMessage()).contains(BLANK_SALT_WARNING));
});
}
@Configuration
@EnableConfigurationProperties(PrivacySettings.class)
static class EnableProperties {}
}
@@ -0,0 +1,54 @@
package dev.caskeleton.composition.runtime.logging;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.annotation.UserConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
/**
* Verifies the composition-root wiring binds the {@link UserPrincipalPseudonymizerPort} port to the
* HMAC implementation keyed with the configured salt (feature-log-management-contract DRIFT-6 /
* Q2).
*/
class PseudonymizationConfigTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(UserConfigurations.of(PseudonymizationConfig.class));
@Test
void wiresAnHmacPseudonymizerThatRedactsThePrincipal() {
runner
.withPropertyValues("ca-skeleton.privacy.pseudonymization-salt=unit-salt-7c")
.run(
context -> {
assertThat(context).hasNotFailed();
UserPrincipalPseudonymizerPort pseudonymizer =
context.getBean(UserPrincipalPseudonymizerPort.class);
String pseudo = pseudonymizer.pseudonymize("idp-user-1");
assertThat(pseudo)
.isNotNull()
.isNotEqualTo("idp-user-1")
.doesNotContain("idp-user-1")
.matches("[0-9a-f]{64}");
// stable for the same input
assertThat(pseudonymizer.pseudonymize("idp-user-1")).isEqualTo(pseudo);
// null/blank pass through as null
assertThat(pseudonymizer.pseudonymize(null)).isNull();
});
}
@Test
void bootsWithTheDevSentinelSaltWhenUnset() {
runner.run(
context -> {
assertThat(context).hasNotFailed();
UserPrincipalPseudonymizerPort pseudonymizer =
context.getBean(UserPrincipalPseudonymizerPort.class);
assertThat(pseudonymizer.pseudonymize("x")).matches("[0-9a-f]{64}");
});
}
}
@@ -0,0 +1,146 @@
package dev.caskeleton.composition.runtime.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.config.MeterFilterReply;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link MetricsCardinalityMeterFilter}.
*
* <p>TDD red-then-green: tests were written before the implementation class existed. Verifies D8
* forbidden-tag deny semantics (feature-metrics-alerting-contract).
*/
class MetricsCardinalityMeterFilterTest {
private final MetricsCardinalityMeterFilter filter = new MetricsCardinalityMeterFilter();
// ----------------------------------------------------------------
// DENY for each forbidden tag key
// ----------------------------------------------------------------
@Test
@DisplayName("D8: accept() returns DENY when tag key is 'user_id'")
void acceptReturnsDenyForUserIdTag() {
Meter.Id id =
new Meter.Id("some.metric", Tags.of("user_id", "abc123"), null, null, Meter.Type.COUNTER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.DENY);
}
@Test
@DisplayName("D8: accept() returns DENY when tag key is 'request_id'")
void acceptReturnsDenyForRequestIdTag() {
Meter.Id id =
new Meter.Id("some.metric", Tags.of("request_id", "req-1"), null, null, Meter.Type.COUNTER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.DENY);
}
@Test
@DisplayName("D8: accept() returns DENY when tag key is 'raw_url'")
void acceptReturnsDenyForRawUrlTag() {
Meter.Id id =
new Meter.Id(
"some.metric", Tags.of("raw_url", "/users/123"), null, null, Meter.Type.COUNTER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.DENY);
}
@Test
@DisplayName("D8: accept() returns DENY when tag key is 'raw_query'")
void acceptReturnsDenyForRawQueryTag() {
Meter.Id id =
new Meter.Id(
"some.metric", Tags.of("raw_query", "name=foo"), null, null, Meter.Type.COUNTER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.DENY);
}
@Test
@DisplayName("D8: accept() returns DENY when tag key is 'raw_header_value'")
void acceptReturnsDenyForRawHeaderValueTag() {
Meter.Id id =
new Meter.Id(
"some.metric",
Tags.of("raw_header_value", "Bearer tok"),
null,
null,
Meter.Type.COUNTER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.DENY);
}
@Test
@DisplayName("D8: accept() returns DENY when tag key is 'ip_address'")
void acceptReturnsDenyForIpAddressTag() {
Meter.Id id =
new Meter.Id(
"some.metric", Tags.of("ip_address", "1.2.3.4"), null, null, Meter.Type.COUNTER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.DENY);
}
@Test
@DisplayName("D8: accept() returns DENY when ANY tag among several is forbidden")
void acceptReturnsDenyWhenAnyTagIsForbidden() {
Meter.Id id =
new Meter.Id(
"some.metric",
Tags.of("status", "200", "user_id", "abc", "uri_template", "/ok"),
null,
null,
Meter.Type.COUNTER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.DENY);
}
// ----------------------------------------------------------------
// NEUTRAL for clean (no forbidden tag) ids
// ----------------------------------------------------------------
@Test
@DisplayName("D8: accept() returns NEUTRAL for clean metric with only allowed tags")
void acceptReturnsNeutralForCleanTags() {
Meter.Id id =
new Meter.Id(
"http.server.requests",
Tags.of("method", "GET", "status", "2xx", "uri_template", "/api/v1/users"),
null,
null,
Meter.Type.TIMER);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.NEUTRAL);
}
@Test
@DisplayName("D8: accept() returns NEUTRAL for metric with no tags")
void acceptReturnsNeutralForNoTags() {
Meter.Id id = new Meter.Id("process.uptime", Tags.empty(), null, null, Meter.Type.GAUGE);
assertThat(filter.accept(id)).isEqualTo(MeterFilterReply.NEUTRAL);
}
// ----------------------------------------------------------------
// Integration with SimpleMeterRegistry
// ----------------------------------------------------------------
@Test
@DisplayName("D8: forbidden-tag meter is not registered in SimpleMeterRegistry")
void forbiddenTagMeterIsDeniedInSimpleRegistry() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
registry.config().meterFilter(filter);
registry.counter("test.metric", "user_id", "abc");
assertThat(registry.find("test.metric").counter())
.as("counter with user_id tag must be denied (not registered)")
.isNull();
}
@Test
@DisplayName("D8: allowed-tag meter IS registered in SimpleMeterRegistry")
void allowedTagMeterIsRegisteredInSimpleRegistry() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
registry.config().meterFilter(filter);
registry.counter("ok.metric", "status", "2xx");
assertThat(registry.find("ok.metric").counter())
.as("counter with only allowed tags must be registered")
.isNotNull();
}
}
@@ -0,0 +1,121 @@
package dev.caskeleton.composition.runtime.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.distribution.HistogramSnapshot;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import java.time.Duration;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* Unit tests for {@link MetricsContractConfig}.
*
* <p>TDD red-then-green: tests were written before the implementation class existed. Verifies that
* {@code MetricsContractConfig.install()} installs both filters (D8 + D9) and that the config is a
* no-op when no {@link MeterRegistry} is available (feature-metrics-alerting-contract).
*/
class MetricsContractConfigTest {
// ----------------------------------------------------------------
// install() — cardinality deny (D8)
// ----------------------------------------------------------------
@Test
@DisplayName("D8: install() makes the registry deny meters with forbidden tags")
void installCausesRegistryToDenyForbiddenTagMeters() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
MetricsContractConfig.install(registry);
registry.counter("test.metric", "user_id", "abc");
assertThat(registry.find("test.metric").counter())
.as("counter with user_id tag must be denied after install()")
.isNull();
}
@Test
@DisplayName("D8: install() allows meters with only clean tags")
void installAllowsMetersWithCleanTags() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
MetricsContractConfig.install(registry);
registry.counter("ok.metric", "status", "2xx");
assertThat(registry.find("ok.metric").counter())
.as("counter with only allowed tags must be registered after install()")
.isNotNull();
}
// ----------------------------------------------------------------
// install() — distribution config for http.server.requests (D9)
// ----------------------------------------------------------------
@Test
@DisplayName(
"D9: install() wires MetricsDistributionMeterFilter so http.server.requests gets SLO histogram buckets")
void installAppliesSloDistributionToHttpServerRequests() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
MetricsContractConfig.install(registry);
// Register and record — the MeterFilter configure() is applied at registration time
Timer timer = registry.timer("http.server.requests");
timer.record(Duration.ofMillis(250));
HistogramSnapshot snapshot = timer.takeSnapshot();
assertThat(snapshot.histogramCounts())
.as(
"install() must wire MetricsDistributionMeterFilter so http.server.requests gets SLO histogram buckets")
.isNotEmpty();
}
// ----------------------------------------------------------------
// the customizer applies both filters at registry construction
// ----------------------------------------------------------------
/**
* The absent-registry case this replaced no longer exists.
*
* <p>It used to construct the configuration with an empty {@code ObjectProvider} and prove the
* {@code @PostConstruct} did not throw. A {@link
* org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryCustomizer} is handed a
* registry by Boot or is never called at all, so "no registry" is structurally unreachable rather
* than a branch worth asserting. What is worth asserting is that the customizer installs both
* filters, because that is what moved.
*/
@Test
@DisplayName("the customizer installs both filters onto the registry it is given")
void customizerInstallsBothFilters() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
new MetricsContractConfig().metricsContractMeterFilters().customize(registry);
registry.counter("http.server.requests", "user_id", "u-1");
assertThat(registry.find("http.server.requests").counter())
.as("a high-cardinality tag is denied by the filter the customizer installed")
.isNull();
}
// ----------------------------------------------------------------
// install() — both filters chain correctly (combined D8+D9)
// ----------------------------------------------------------------
@Test
@DisplayName("D8+D9: install() chains cardinality DENY before distribution config")
void installChainsBothFilters() {
SimpleMeterRegistry registry = new SimpleMeterRegistry();
MetricsContractConfig.install(registry);
// Forbidden tag: denied (D8 wins first)
registry.counter("some.metric", "ip_address", "10.0.0.1");
assertThat(registry.find("some.metric").counter())
.as("meter with ip_address must be denied by D8 filter")
.isNull();
// Clean metric: registered (D9 applied for timers)
registry.timer("db.query.duration", "operation", "select", "outcome", "SUCCESS");
assertThat(registry.find("db.query.duration").timer())
.as("db.query.duration timer with clean tags must be registered")
.isNotNull();
}
}
@@ -0,0 +1,154 @@
package dev.caskeleton.composition.runtime.metrics;
import static org.assertj.core.api.Assertions.assertThat;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.distribution.DistributionStatisticConfig;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Unit tests for {@link MetricsDistributionMeterFilter}.
*
* <p>TDD red-then-green: tests were written before the implementation class existed. Verifies D9
* SLO-driven histogram and percentile configuration for owned timers
* (feature-metrics-alerting-contract).
*/
class MetricsDistributionMeterFilterTest {
private final MetricsDistributionMeterFilter filter = new MetricsDistributionMeterFilter();
// ----------------------------------------------------------------
// Owned timers get SLO-driven configuration
// ----------------------------------------------------------------
@ParameterizedTest(name = "D9: configure() applies SLO histogram to owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
void configureAppliesSloHistogramToOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
assertThat(result.isPercentileHistogram())
.as("owned timer '%s' must have percentileHistogram=true (D9 aggregable)", metricName)
.isTrue();
}
@ParameterizedTest(name = "D9: configure() sets non-empty SLO boundaries for owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
void configureSetsSloBoundariesForOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
double[] slos = result.getServiceLevelObjectiveBoundaries();
assertThat(slos)
.as("owned timer '%s' must have non-null, non-empty SLO boundaries", metricName)
.isNotNull()
.isNotEmpty();
// Expect 4 SLO boundaries: 100ms, 500ms, 1s, 5s (in nanos)
assertThat(slos).hasSize(4);
}
@ParameterizedTest(name = "D9: configure() sets client-side percentiles for owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
void configureSetsPercentilesForOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
double[] percentiles = result.getPercentiles();
assertThat(percentiles)
.as("owned timer '%s' must have percentiles set", metricName)
.isNotNull()
.containsExactlyInAnyOrder(0.5, 0.9, 0.95, 0.99);
}
@ParameterizedTest(name = "D9: configure() sets min/max expected value for owned timer ''{0}''")
@ValueSource(
strings = {
"http.server.requests",
"http.server.requests.latency",
"dependency.client.requests",
"db.query.duration",
"jvm.gc.pause"
})
void configureSetsMinMaxExpectedValueForOwnedTimers(String metricName) {
Meter.Id id = new Meter.Id(metricName, Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
assertThat(result.getMinimumExpectedValueAsDouble())
.as("owned timer '%s' must have minimumExpectedValue set", metricName)
.isNotNull()
.isPositive();
assertThat(result.getMaximumExpectedValueAsDouble())
.as("owned timer '%s' must have maximumExpectedValue set", metricName)
.isNotNull()
.isPositive();
}
// ----------------------------------------------------------------
// Non-owned metrics pass through unchanged
// ----------------------------------------------------------------
@Test
@DisplayName("D9: configure() returns config unchanged for non-owned metric 'lock.acquisition'")
void configurePassesThroughNonOwnedCounter() {
Meter.Id id = new Meter.Id("lock.acquisition", Tags.empty(), null, null, Meter.Type.COUNTER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
assertThat(result.isPercentileHistogram())
.as("non-owned metric must not have percentileHistogram changed")
.isFalse();
assertThat(result.getServiceLevelObjectiveBoundaries())
.as("non-owned metric must not have SLO boundaries set")
.isNull();
}
@Test
@DisplayName(
"D9: configure() returns config unchanged for non-owned timer 'resilience4j.circuitbreaker.calls'")
void configurePassesThroughNonOwnedTimer() {
Meter.Id id =
new Meter.Id(
"resilience4j.circuitbreaker.calls", Tags.empty(), null, null, Meter.Type.TIMER);
DistributionStatisticConfig result = filter.configure(id, DistributionStatisticConfig.DEFAULT);
assertThat(result.isPercentileHistogram())
.as("consumed-but-not-owned timer must not have percentileHistogram forced")
.isFalse();
}
@Test
@DisplayName("D9: configure() returns same instance for non-owned metric")
void configureReturnsSameInstanceForNonOwnedMetric() {
Meter.Id id = new Meter.Id("lock.acquisition", Tags.empty(), null, null, Meter.Type.COUNTER);
DistributionStatisticConfig original = DistributionStatisticConfig.DEFAULT;
DistributionStatisticConfig result = filter.configure(id, original);
assertThat(result)
.as("non-owned metric must return the same config instance unchanged")
.isSameAs(original);
}
}
@@ -0,0 +1,56 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import org.junit.jupiter.api.Test;
/**
* D12 계약 검증: {@link MicrometerSpanErrorRecorder}가 현재 span에 예외와 error.code 태그를 기록하는지, null/no-span
* 케이스를 no-op 처리하는지.
*/
class MicrometerSpanErrorRecorderTest {
@Test
void recordsErrorAndErrorCodeOnCurrentSpan() {
Tracer tracer = mock(Tracer.class);
Span span = mock(Span.class);
when(tracer.currentSpan()).thenReturn(span);
when(span.error(any())).thenReturn(span);
when(span.tag(anyString(), anyString())).thenReturn(span);
SpanErrorRecorder recorder = new MicrometerSpanErrorRecorder(tracer);
RuntimeException boom = new RuntimeException("boom");
recorder.recordException(boom, "INTERNAL_ERROR");
verify(span).error(boom);
verify(span).tag("error.code", "INTERNAL_ERROR");
}
@Test
void nullErrorIsNoOp() {
Tracer tracer = mock(Tracer.class);
SpanErrorRecorder recorder = new MicrometerSpanErrorRecorder(tracer);
recorder.recordException(null, "X"); // must not throw
verifyNoInteractions(tracer);
}
@Test
void noCurrentSpanIsNoOp() {
Tracer tracer = mock(Tracer.class);
when(tracer.currentSpan()).thenReturn(null);
SpanErrorRecorder recorder = new MicrometerSpanErrorRecorder(tracer);
recorder.recordException(new RuntimeException("boom"), "X"); // must not throw
}
}
@@ -0,0 +1,92 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* required_test: {@code tracing-contract:sample-rate-per-profile}
* (feature-distributed-tracing-contract D6).
*/
class TracingSampleRateResolverTest {
private final TracingSampleRateResolver resolver = new TracingSampleRateResolver();
// ---- defaultRateForProfile ----
@Test
void prodProfileDefaultIsOnePercent() {
assertThat(TracingSampleRateResolver.defaultRateForProfile("prod")).isEqualTo(0.01);
}
@Test
void devProfileDefaultIsOneHundredPercent() {
assertThat(TracingSampleRateResolver.defaultRateForProfile("dev")).isEqualTo(1.0);
}
@Test
void localProfileDefaultIsOneHundredPercent() {
assertThat(TracingSampleRateResolver.defaultRateForProfile("local")).isEqualTo(1.0);
}
@ParameterizedTest
@ValueSource(strings = {"staging", "qa", "test", "integration", ""})
void unknownProfileDefaultIsOneHundredPercent(String profile) {
assertThat(TracingSampleRateResolver.defaultRateForProfile(profile)).isEqualTo(1.0);
}
@Test
void nullProfileDefaultIsOneHundredPercent() {
assertThat(TracingSampleRateResolver.defaultRateForProfile(null)).isEqualTo(1.0);
}
// ---- resolve: configured override wins over profile default ----
@Test
void configuredRateOverridesProfileDefaultWhenValid() {
// required_test: tracing-contract:sample-rate-per-profile
// 0.25 is a valid float in [0,1], overrides prod's default of 0.01
assertThat(resolver.resolve("prod", "0.25")).isEqualTo(0.25);
}
@Test
void configuredRateZeroIsValidOverride() {
assertThat(resolver.resolve("local", "0.0")).isEqualTo(0.0);
}
@Test
void configuredRateOneIsValidOverride() {
assertThat(resolver.resolve("prod", "1.0")).isEqualTo(1.0);
}
@Test
void blankConfiguredRateFallsThroughToProfileDefault() {
assertThat(resolver.resolve("prod", "")).isEqualTo(0.01);
assertThat(resolver.resolve("prod", " ")).isEqualTo(0.01);
}
@Test
void nullConfiguredRateFallsThroughToProfileDefault() {
assertThat(resolver.resolve("prod", null)).isEqualTo(0.01);
}
@Test
void outOfRangeConfiguredRateFallsThroughToProfileDefault() {
// 1.5 is out of [0,1] — falls through to profile default
assertThat(resolver.resolve("prod", "1.5")).isEqualTo(0.01);
}
@Test
void nonNumericConfiguredRateFallsThroughToProfileDefault() {
assertThat(resolver.resolve("prod", "not-a-number")).isEqualTo(0.01);
}
@Test
void multipleOrUnknownProfilesDoNotInventALocalRuntime() {
assertThat(resolver.resolve(java.util.List.of("local", "prod"), null)).isEqualTo(1.0);
assertThat(resolver.resolve(java.util.List.of("staging"), null)).isEqualTo(1.0);
assertThat(resolver.resolve(java.util.List.of(), null)).isEqualTo(1.0);
}
}
@@ -0,0 +1,59 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.mock.env.MockEnvironment;
/**
* D-1 (ISSUE-1 해소): {@link TracingSamplingEnvironmentPostProcessor}가 유효 샘플링 비율을 {@code
* management.tracing.sampling.probability}로 브리지하는지 검증.
*/
class TracingSamplingEnvironmentPostProcessorTest {
private final TracingSamplingEnvironmentPostProcessor epp =
new TracingSamplingEnvironmentPostProcessor();
@Test
void prodProfileBlankRateResolvesToOnePercent() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
// APP_TRACING_SAMPLE_RATE 미설정(blank) — per-profile 기본값이 적용돼야 한다.
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.01");
}
@Test
void profilelessContextDoesNotInventALocalRuntimeButUsesTheSafeNonProductionRate() {
MockEnvironment env = new MockEnvironment();
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("1.0");
}
@Test
void explicitRateWins() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
env.setProperty("ca-skeleton.tracing.sample-rate", "0.25");
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.25");
}
@Test
void doesNotOverrideExplicitProbability() {
MockEnvironment env = new MockEnvironment();
env.setActiveProfiles("prod");
env.setProperty("management.tracing.sampling.probability", "0.5");
epp.postProcessEnvironment(env, new SpringApplication());
assertThat(env.getProperty("management.tracing.sampling.probability")).isEqualTo("0.5");
}
}
@@ -0,0 +1,214 @@
package dev.caskeleton.composition.runtime.tracing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Configuration;
/**
* Settings binding + validation tests for {@link TracingSettings}
* (feature-distributed-tracing-contract — required_tests: {@code
* tracing-contract:exporter-endpoint-resolvable} / {@code
* tracing-contract:sample-rate-per-profile}).
*/
class TracingSettingsTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(EnableProperties.class);
// ---- sampleRate binding and validation ----
@Test
void validSampleRateIsBoundAndParseable() {
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=0.5",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(
ctx -> {
assertThat(ctx).hasNotFailed();
TracingSettings props = ctx.getBean(TracingSettings.class);
assertThat(props.sampleRate()).isEqualTo("0.5");
assertThat(props.sampleRateValue()).isEqualTo(0.5);
});
}
@Test
void sampleRateZeroIsValidBoundary() {
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=false",
"ca-skeleton.tracing.sample-rate=0.0",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(
ctx -> {
assertThat(ctx).hasNotFailed();
assertThat(ctx.getBean(TracingSettings.class).sampleRateValue()).isEqualTo(0.0);
});
}
@Test
void sampleRateOneIsValidBoundary() {
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=1.0",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(
ctx -> {
assertThat(ctx).hasNotFailed();
assertThat(ctx.getBean(TracingSettings.class).sampleRateValue()).isEqualTo(1.0);
});
}
@Test
void invalidSampleRateAboveOneFailsStartup() {
// required_test: tracing-contract:exporter-endpoint-resolvable (sampleRate sub-case)
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=1.5",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(ctx -> assertThat(ctx).hasFailed());
}
@Test
void invalidSampleRateNonNumericFailsStartup() {
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=not-a-number",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(ctx -> assertThat(ctx).hasFailed());
}
@Test
void negativeSampleRateFailsStartup() {
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=-0.1",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(ctx -> assertThat(ctx).hasFailed());
}
// ---- otlpEndpoint validation (required_test: tracing-contract:exporter-endpoint-resolvable)
// ----
@Test
void emptyOtlpEndpointPassesValidation() {
// required_test: tracing-contract:exporter-endpoint-resolvable (empty = exporter off)
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=1.0",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(
ctx -> {
assertThat(ctx).hasNotFailed();
assertThat(ctx.getBean(TracingSettings.class).exporter().otlpEndpoint()).isBlank();
});
}
@Test
void validUrlEndpointPassesValidation() {
// required_test: tracing-contract:exporter-endpoint-resolvable (valid URL)
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=1.0",
"ca-skeleton.tracing.exporter.otlp-endpoint=http://otel-collector:4317")
.run(
ctx -> {
assertThat(ctx).hasNotFailed();
assertThat(ctx.getBean(TracingSettings.class).exporter().otlpEndpoint())
.isEqualTo("http://otel-collector:4317");
});
}
@Test
void malformedEndpointFailsStartup() {
// required_test: tracing-contract:exporter-endpoint-resolvable (malformed URL)
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=1.0",
"ca-skeleton.tracing.exporter.otlp-endpoint=not a valid url$$")
.run(ctx -> assertThat(ctx).hasFailed());
}
@Test
void endpointWithSpacesFailsStartup() {
// url_or_empty: URI.create throws on illegal characters (spaces)
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=true",
"ca-skeleton.tracing.sample-rate=1.0",
"ca-skeleton.tracing.exporter.otlp-endpoint=not valid url")
.run(ctx -> assertThat(ctx).hasFailed());
}
@Test
void enabledFlagIsBoundCorrectly() {
runner
.withPropertyValues(
"ca-skeleton.tracing.enabled=false",
"ca-skeleton.tracing.sample-rate=1.0",
"ca-skeleton.tracing.exporter.otlp-endpoint=")
.run(
ctx -> {
assertThat(ctx).hasNotFailed();
assertThat(ctx.getBean(TracingSettings.class).enabled()).isFalse();
});
}
// ---- D-1 (ISSUE-1): blank sampleRate pass-through ----
@Test
void blankSampleRateIsPreservedAsBlankNotCoercedToOne() {
// Before fix: "" -> "1.0" coercion. After fix: blank preserved → resolver applies per-profile
// default.
TracingSettings settings = new TracingSettings(true, "", null);
assertThat(settings.sampleRate()).isBlank();
}
@Test
void blankSampleRatePassesValidation() {
// blank = "per-profile default" signal → must not throw at construction
assertThatNoException().isThrownBy(() -> new TracingSettings(true, " ", null));
}
@Test
void nonBlankInvalidSampleRateStillThrows() {
assertThatThrownBy(() -> new TracingSettings(true, "1.5", null))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED));
}
// ---- F3: sampleRateValue() precondition contract ----
/**
* Blank sampleRate means "defer to per-profile default"; calling sampleRateValue() when the rate
* is blank is a caller contract violation. Must throw {@link IllegalStateException} with a clear
* message — NOT a cryptic NFE.
*/
@Test
void sampleRateValueThrowsIllegalStateExceptionWhenBlank() {
TracingSettings settings = new TracingSettings(true, "", null);
assertThatThrownBy(settings::sampleRateValue)
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("blank");
}
@Configuration
@EnableConfigurationProperties(TracingSettings.class)
static class EnableProperties {}
}