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

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

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

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-29 12:30:01 +09:00
co-authored by Claude Opus 5.5
parent 25de288ab4
commit 423a29c46f
329 changed files with 6380 additions and 6850 deletions
+8 -5
View File
@@ -62,14 +62,17 @@ configurations, Redis as one 376-line class.
switch registry, no cross-capability dependency validator, no activation endpoint. Component scan
covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`, `WebSecurityAutoConfiguration`) and support
(`OutboundSupportConfig`) arrive through their own `AutoConfiguration.imports`. What stays in `autoconfigure/<name>/` is application
composition over application-core ports that names no module type: `outbox` (the relay use case
and its scheduler, on only when the store and publisher ports exist), `operation` (the durable
composition over application-core ports that names no module type: `operation` (the durable
operation use cases and their `/operations` endpoints, on only when the operation store and the
outbox append port exist), `idempotency` (the one executor over whichever store is selected),
`tracing`, `common`.
outbox append port exist), `common`. The outbox relay and the idempotency executor are
`composition:outbox-relay` and `composition:idempotency`, selected by one `runtimeOnly` line each
(the sample takes the idempotency one too). The runtime wiring both composition roots need —
tracing, the metrics contract filters, domain-context propagation, user-principal pseudonymization
(`PrivacySettings`) and the actuator chain — is `composition:service-runtime`, which the sample
takes by the same line instead of carrying copies.
- **`<Capability>Settings` lives beside its capability**, not in `settings/`. The `settings/` package
holds only settings that belong to no capability — `BootstrapSettings`, `LoggingSettings`,
`PrivacySettings`, `RuntimeSafetySettings`.
`RuntimeSafetySettings`.
- **`runtime/` holds guards about the application itself** — secrets, numeric bounds, error-detail
exposure, multi-instance coordination, the runtime-profile check (`RuntimeEnvironmentProfileValidator`).
A guard about a capability's settings (the JPA OSIV/DDL/pool/TLS/vendor guards, the Mongo
+18 -316
View File
@@ -41,14 +41,12 @@ WebSocket, gRPC, 파일 서버, 알림)는 `build.gradle`에 주석 처리된 `r
- [runtime/startup — Fail-fast 시작 파이프라인](#runtimestartup--fail-fast-시작-파이프라인과-시작-실패-분류)
- [runtime — 시크릿 소스 선택과 런타임 안전 가드](#runtime--시크릿-소스-선택과-런타임-안전-가드)
- [concurrency — 도메인 컨텍스트 전파](#concurrency--도메인-컨텍스트-전파-전략-조립)
- [concurrency — 도메인 컨텍스트 전파 (composition:service-runtime으로 이동)](#concurrency--도메인-컨텍스트-전파-compositionservice-runtime으로-이동)
- [async — 비동기 executor 컨텍스트 전파와 포화 처리](#async--비동기-executor-컨텍스트-전파와-포화-처리)
- [idempotency — 멱등성 provider 선택과 executor 조립](#idempotency--멱등성-provider-선택과-executor-조립)
- [outbox — 트랜잭셔널 아웃박스 릴레이](#outbox--트랜잭셔널-아웃박스-릴레이-와이어링)
- [idempotency — 멱등성 executor 조립 (composition:idempotency로 이동)](#idempotency--멱등성-executor-조립-compositionidempotency로-이동)
- [outbox — 트랜잭셔널 아웃박스 릴레이 (composition:outbox-relay로 이동)](#outbox--트랜잭셔널-아웃박스-릴레이-compositionoutbox-relay로-이동)
- [logging — 로그 시크릿 마스킹·샘플링·가명화](#logging--로그-시크릿-마스킹샘플링가명화)
- [metrics — 메트릭 계약 MeterFilter](#metrics--메트릭-계약-meterfilter-설치)
- [management/security — 액추에이터 엔드포인트 보안](#managementsecurity--액추에이터-엔드포인트-보안-체인)
- [tracing — 분산 트레이싱 wiring과 샘플링 정책](#tracing--분산-트레이싱-wiring과-샘플링-정책)
- [metrics·management/security·tracing (composition:service-runtime으로 이동)](#metricsmanagementsecuritytracing-compositionservice-runtime으로-이동)
- [settings — @ConfigurationProperties 검증 정책](#settings--configurationproperties-검증-정책)
- [build.gradle — 의존성 구성 근거](#buildgradle--의존성-구성-근거)
@@ -188,15 +186,9 @@ README의 "startup" 절에 있다.
---
## concurrency — 도메인 컨텍스트 전파 전략 조립
## concurrency — 도메인 컨텍스트 전파 (composition:service-runtime으로 이동)
### DomainContextConfig
- **`DomainContextPropagator`를 빈으로 노출하고 `ThreadLocalDomainContextPropagator`를 직접 만든다.**
`application-core`는 설정을 직접 읽지 않으므로 propagator 생성은 composition root(여기)에서 끝내고
완성된 propagator만 주입한다. 제공하는 전략이 하나뿐이라 선택 설정(strategy enum·factory·설정 키)은
두지 않는다. 두 번째 전략이 생기면 그 구현과 선택 설정을 함께 추가한다.
---
`DomainContextConfig`는 `composition:service-runtime`으로 옮겼다. 근거는 [그 모듈의 README](../composition/service-runtime/README.md).
## async — 비동기 executor 컨텍스트 전파와 포화 처리
@@ -277,132 +269,19 @@ README의 "startup" 절에 있다.
---
## idempotency — 멱등성 provider 선택과 executor 조립
## idempotency — 멱등성 executor 조립 (composition:idempotency로 이동)
### IdempotencyProviderSelectionConfig
- **`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` 를 쓴다.
executor 조립(`IdempotencyAutoConfiguration`)과 수명 정책(`IdempotencySettings`, strict 바인딩),
설정 기본값(`config/module-defaults/idempotency.yml`, 예전 `config/capabilities.yml`)은
`composition:idempotency`로 옮겼다(소유자 결정 3). 이 leaf는 `runtimeOnly` 한 줄로 받고,
sample-portfolio도 같은 줄을 쓴다. 근거는 [그 모듈의 README](../composition/idempotency/README.md).
### IdempotencySettings
- `ca-skeleton.capabilities.idempotency` 에 바인딩되는 유일한 설정 record 다(값은
`config/capabilities.yml`).
## outbox — 트랜잭셔널 아웃박스 릴레이 (composition:outbox-relay로 이동)
| 키 | 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` 일 때만 돈다.
---
## outbox — 트랜잭셔널 아웃박스 릴레이 와이어링
### OutboxConfig
- **릴레이 use case 를 `@Service`가 아니라 `app-bootstrap`에서 수동 조립한다.**
`PublishPendingOutboxEventsUseCase`는 `batchSize`와 `inFlightTimeout` 같은 설정값을 생성자로 받아야
하는데, `application-core`는 설정(`OutboxSettings`)을 직접 읽으면 안 된다. 그래서 설정을 볼 수 있는
합성 루트(`OutboxConfig`)가 값을 꺼내 use case 를 손으로 만들어 넘긴다. use case 클래스의
`@UseCaseCapability` 애너테이션은 와이어링 방식과 무관하게 유지된다(ArchUnit 이 강제).
- **bootstrap은 failure reporter를 구현하지 않고 주입만 한다.** `MessagingConfig`가 broker 설정에서
정확히 하나의 `OutboxRelayFailureReportPort` 구현을 만들고, `OutboxConfig`는 이를 relay 생성자에
전달한다. broker가 비활성이어도 reporter bean은 존재한다.
- **릴레이 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가 있고
켜져 있는데 broker가 비었고 canonical transport도 없으면 기동을 거부한다.
- **왜 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 가
(위 OutboxConfig 사유로) 일부러 빈이 아니기 때문에, 그 use case 를 조립하는 `OutboxConfig`가
스케줄러 등록까지 같이 소유한다.
- **릴레이 사이클에서 발생하는 예상치 못한 예외를 잡아 ERROR 로 로깅만 하고 삼킨다.** 스케줄러
스레드가 죽으면 릴레이가 조용히 멈추므로, 다음 틱을 위해 스레드를 살려둔다. 단, 개별 발행 실패
(FAILED/DEAD 전이)는 relay가 persisted transition 성공 뒤 typed reporter로 canonical ERROR를
요청하고 결과에 반영하므로 이 catch 블록까지 오지 않는다 — 여기서 삼키는 것은 어디까지나
"예상치 못한" 예외다.
- **스케줄링은 `OutboxConfig`가 직접 켜고(`@EnableScheduling`) fixed-delay 를 쓴다.** 예전에는 JDBC
idempotency 설정만 스케줄링을 켰기 때문에 다른 provider 를 고르면 릴레이가 조립만 되고 돌지
않았다. fixed-delay 는 릴레이 실행 시간과 무관하게 사이클이 겹치지 않도록(non-overlapping) 보장한다.
### OutboxSettings
- **여섯 개 설정값 모두 코드 리터럴 기본값을 쓰고 env placeholder 를 두지 않는다.** 신규 env key 를
추가하지 않는다는 결정에 따라, 값이 없으면 컴팩트 생성자에서 직접 기본값(예: `PT5S`, `20`,
`PT5M`, `PT10M`, `P7D`)을 채운다.
- **`reaper-interval`과 `published-retention`은 `adapter-persistence`의 `OutboxReaper`도 property
문자열로 읽는다.** 두 모듈이 같은 키를 공유하지만, 이 properties record 가 여섯 값 전체를 문서화
하는 단일 지점(single place) 역할을 한다. 기본값 yml(`ca-skeleton.outbox.*`)은 store를 가진
persistence-jpa 모듈이 `config/module-defaults/persistence-jpa.yml`로 가져온다.
---
relay 조립(`OutboxRelayAutoConfiguration`, 스케줄러·metrics·leader token·`OutboxSettings`)은
`composition:outbox-relay`로 옮겼다(소유자 결정 3 — persistence-jpa가 아닌 이유는 ArchUnit
`PERSISTENCE_DOES_NOT_DEPEND_ON_APPLICATION_SERVICES`). 이 leaf는 `runtimeOnly` 한 줄로 받는다.
근거는 [그 모듈의 README](../composition/outbox-relay/README.md).
## logging — 로그 시크릿 마스킹·샘플링·가명화
@@ -433,16 +312,6 @@ README의 "startup" 절에 있다.
루트 레벨을 TRACE 로 낮춰야만 가능한 `TRACE` 드롭은 상위 클래스가 여전히 버리지만 카운트하지는
않아서, 태그 카디널리티가 레지스트리 계약을 벗어나지 않게 유지한다.
### PseudonymizationConfig
- **`user_principal`(로그에 남는 사용자 식별자)를 전체 HMAC 방식으로 가명화한다.**
`UserPrincipalPseudonymizerPort`(application-core)를 HMAC-SHA-256 구현(adapter-identifier)에
바인딩하고, 솔트는 `PrivacySettings`에서 가져온다. 원본 식별자를 그대로 로그에 남기지 않으려는
개인정보 보호 결정이다. 실제 사용처는 `adapter-web`의 `RequestLoggingFilter`로, 보안 principal 이
MDC/로그에 닿기 전에 이 포트로 가린다.
- **`@ConditionalOnMissingBean`으로 기본 구현을 둔다.** 이 템플릿을 포크한 프로젝트가 자기만의
가명화기(예: 향후 솔트 회전을 지원하는 구현)를 등록하면 이 기본 빈이 비켜주도록, 즉 기본값은
제공하되 교체를 막지 않도록 하기 위해서다.
### SamplingTurboFilter
- **레벨을 의식하는 로그 샘플러다.** `WARN`/`ERROR`는 절대 샘플링하지 않고 항상 통과시킨다
(`FilterReply.NEUTRAL`). 진단·장애 신호인 경고/오류는 100% 보장해야 하고, 샘플링 대상은 `INFO`
@@ -472,164 +341,9 @@ README의 "startup" 절에 있다.
---
## metrics — 메트릭 계약 MeterFilter 설치
## metrics·management/security·tracing (composition:service-runtime으로 이동)
### 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()`이 직접 인스턴스화하기 위한 계약이다.
---
## 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`)가 이를 정적
으로 강제한다.
---
## 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 분기가 없어도 실제 성능 부담은 없다.
---
메트릭 계약 filter(`MetricsContractConfig`), actuator 보안 chain(`ManagementSecurityConfig`), tracing 배선(`TracingConfig` 외 5개), 가명화(`PseudonymizationConfig`·`PrivacySettings`)는 `composition:service-runtime`으로 옮겼다. 근거는 [그 모듈의 README](../composition/service-runtime/README.md).
## settings — @ConfigurationProperties 검증 정책
@@ -654,18 +368,6 @@ README의 "startup" 절에 있다.
- **size 문자열(`maxSize`, `totalSizeCap`)은 검증하지 않는다.** 이 값들의 파싱 계약은 logback 이
소유하므로 logback 에게 맡긴다.
### 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 의
책임 밖이라 여기서 중복 강제하지 않는다.
### RuntimeSafetySettings
- **시작 시 `StartupSafetyValidator`가 강제하는 운영 안전 설정이다.** 현재 구현된 runtime
contract는 `APP_MULTI_INSTANCE_ENABLED`이며, 활성화 시 cross-instance `DistributedLockPort`가
+14 -1
View File
@@ -154,6 +154,17 @@ dependencies {
// runtimeOnly project(':composition:fileserver-platform') // 파일 서버
// runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa 줄도 함께 푼다)
// 기본 조립에 있는 application composition. 둘 다 포트만 보고, 필요한 것(outbox store, 멱등성
// provider)이 없으면 아무것도 만들지 않는다. sample-portfolio도 같은 멱등성 모듈을 쓴다.
runtimeOnly project(':composition:outbox-relay') // outbox relay (store·발행 포트가 있을 때만)
runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor (provider≠disabled)
// 모든 서비스가 받는 runtime 배선: tracing, metrics 계약 filter, domain context, user principal
// 가명화, actuator 보안 chain. sample-portfolio도 같은 줄을 쓴다.
runtimeOnly project(':composition:service-runtime')
// Contract tests pin those pieces by type (tracing gauge, metrics filters, actuator chain).
testImplementation project(':composition:service-runtime')
integrationTestImplementation project(':composition:service-runtime')
capabilityProjects.each { architectureTestRuntimeOnly project(it) }
// The sample is the reference adopters copy, so the whole-repository rules read it too (review
// BUILD-중복-8). Architecture-test runtime only: no production configuration reaches it.
@@ -168,6 +179,8 @@ dependencies {
// would, and turns off whichever one a test is not about.
integrationTestImplementation project(':composition:fileserver-platform')
integrationTestImplementation project(':adapter:inbound:web-fileserver')
// PostgreSqlIdempotencyProviderIntegrationTest composes the executor module over the real store.
integrationTestImplementation project(':composition:idempotency')
testImplementation(testFixtures(project(':adapter:outbound:persistence-jpa')))
testImplementation(testFixtures(project(':adapter:inbound:web')))
@@ -196,7 +209,7 @@ dependencies {
// Actuator + Prometheus registry (health/info/prometheus/loggers endpoints).
implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'io.micrometer:micrometer-registry-prometheus'
// Security types for ManagementSecurityConfig (not reachable via adapter-web's implementation dep). See README.
// Spring Security on the runtime graph (the actuator chain itself is composition:service-runtime's). See README.
implementation 'org.springframework.boot:spring-boot-starter-security'
// test-only: ArchUnit needs actuator types to verify the health-shape guardrail. See README.
@@ -687,7 +687,11 @@ class ApplicationBoundaryArchitectureTest {
*/
private static boolean isInProcessDrivenOutbound(String packageName) {
return packageName.contains(".adapter.outbound.persistence")
|| packageName.contains(".adapter.outbound.identifier");
|| packageName.contains(".adapter.outbound.identifier")
// The template's IntegrationEventEncoderPort: a deterministic in-memory rendering of the
// application's own envelope, no IO — the same shape as the identifier codecs. Only this
// package; the rest of support stays covered.
|| packageName.contains(".adapter.outbound.support.messaging");
}
@ArchTest
@@ -63,7 +63,7 @@ class StartupFailureContractArchitectureTest {
* per-profile default"; calling the accessor anyway is a bug in the caller, not in configuration.
*/
private static final String TRACING_SETTINGS =
"dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSettings";
"dev.caskeleton.composition.runtime.tracing.TracingSettings";
/**
* {@code RedisKeys} — two JCE invariants ("HmacSHA256 must be available", "a Mac must be
@@ -151,7 +151,7 @@ class TypeBoundaryArchitectureTest {
.and(implementsApplicationLayerPort()))
// @Configuration factory classes are excluded: a @Bean method legitimately
// returns the adapter's own outbound port type for DI wiring (e.g.
// MessagingConfig#messagePublisher -> MessagePublisher) — that is
// MessagingConfig#outboxMessagePublishPort -> OutboxMessagePublishPort) — that is
// composition-root assembly, not an adapter *response* method leaking an
// external type. B7 targets the latter (ACL leakage), not DI factories
// (feature-integration-adapter-templates Layer 1 @ConditionalOnProperty configs).
@@ -4,12 +4,10 @@ import dev.caskeleton.application.capability.Idempotency;
import dev.caskeleton.application.capability.RepositoryAccess;
import dev.caskeleton.application.capability.UseCaseCapability;
import dev.caskeleton.application.command.Command;
import dev.caskeleton.application.outbox.OutboxEvent;
import dev.caskeleton.application.outbox.OutboxEventStatus;
import dev.caskeleton.application.outbox.ClaimedOutboxEvent;
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
import dev.caskeleton.application.transaction.TransactionMode;
import dev.caskeleton.application.usecase.CommandUseCase;
import java.time.Instant;
/**
* Intentional violation of {@code
@@ -27,24 +25,17 @@ public final class OutboundWithoutPermissionUseCase
implements CommandUseCase<OutboundWithoutPermissionUseCase.DummyCommand, Void> {
private final OutboxMessagePublishPort publisher;
private final ClaimedOutboxEvent event;
public OutboundWithoutPermissionUseCase(OutboxMessagePublishPort publisher) {
public OutboundWithoutPermissionUseCase(
OutboxMessagePublishPort publisher, ClaimedOutboxEvent event) {
this.publisher = publisher;
this.event = event;
}
@Override
public Void handle(DummyCommand input) {
publisher.publish(
new OutboxEvent(
"event-1",
"fixture.created",
"aggregate-1",
"{}",
Instant.EPOCH,
"correlation-1",
"idempotency-1",
OutboxEventStatus.PENDING,
0));
publisher.publish(event);
return null;
}
@@ -25,7 +25,8 @@ import org.springframework.scheduling.annotation.Scheduled;
* genuinely needs fixed-rate must first prove idempotency and relax this rule deliberately.
*
* <p>Every production {@code @Scheduled} today ({@code IdempotencyReaper}, {@code OutboxReaper},
* {@code OutboxRelayScheduler}) uses {@code fixedDelayString} — this rule pins that.
* {@code OutboxRelayScheduler} in composition:outbox-relay) uses {@code fixedDelayString} — this
* rule pins that.
*/
@AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class)
class ScheduledJobOverlapPolicyTest {
@@ -8,9 +8,9 @@ import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapp
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.bootstrap.async.AsyncContextTaskDecorator;
import dev.caskeleton.bootstrap.concurrency.DomainContextConfig;
import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer;
import dev.caskeleton.composition.fileserver.FileserverPlatformAutoConfiguration;
import dev.caskeleton.composition.runtime.context.DomainContextConfig;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -8,8 +8,8 @@ import dev.caskeleton.application.idempotency.IdempotentAction;
import dev.caskeleton.application.idempotency.IdempotentResponseCodec;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import dev.caskeleton.application.transaction.OperationId;
import dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig;
import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer;
import dev.caskeleton.composition.idempotency.IdempotencyAutoConfiguration;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@@ -108,7 +108,7 @@ class PostgreSqlIdempotencyProviderIntegrationTest {
JdbcTemplateAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
FlywayAutoConfiguration.class,
IdempotencyProviderSelectionConfig.class))
IdempotencyAutoConfiguration.class))
.withUserConfiguration(Class.forName(POSTGRESQL_STORE_CONFIG))
.withPropertyValues(
"ca-skeleton.capabilities.idempotency.provider=postgresql",
@@ -12,8 +12,8 @@ import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice;
import dev.caskeleton.bootstrap.concurrency.DomainContextConfig;
import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer;
import dev.caskeleton.composition.runtime.context.DomainContextConfig;
import java.util.List;
import java.util.Set;
import org.flywaydb.core.Flyway;
@@ -110,7 +110,7 @@ class DurableOperationCompositionIntegrationTest {
String.class,
operationId),
jdbc.queryForList("SELECT event_type FROM outbox_event", String.class)))
.containsExactly("PENDING", List.of("DurableOperationSubmitted"));
.containsExactly("PENDING", List.of("durable-operation.submitted"));
}
@Test
@@ -20,7 +20,6 @@ import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
@ConfigurationPropertiesScan(
basePackages = {
"dev.caskeleton.bootstrap.async",
"dev.caskeleton.bootstrap.concurrency",
"dev.caskeleton.bootstrap.runtime",
"dev.caskeleton.bootstrap.security",
"dev.caskeleton.bootstrap.settings"
@@ -1,56 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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 org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
/**
* 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.
*
* <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.
*/
@AutoConfiguration
@EnableConfigurationProperties(IdempotencySettings.class)
public class IdempotencyProviderSelectionConfig {
@Bean
@ConditionalOnExpression(
"!'${ca-skeleton.capabilities.idempotency.provider:disabled}'.trim()"
+ ".equalsIgnoreCase('disabled')")
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(java.util.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());
}
}
@@ -1,93 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.idempotency;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 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.
*
* @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
*/
@ConfigurationProperties(prefix = IdempotencySettings.PREFIX)
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";
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);
}
}
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
}
}
@@ -1,11 +1,13 @@
package dev.caskeleton.bootstrap.autoconfigure.operation;
import dev.caskeleton.adapter.inbound.web.operation.DurableOperationController;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.operation.CancelDurableOperationUseCase;
import dev.caskeleton.application.operation.DurableOperationStorePort;
import dev.caskeleton.application.operation.DurableOperationSubmittedContract;
import dev.caskeleton.application.operation.GetDurableOperationUseCase;
import dev.caskeleton.application.operation.SubmitDurableOperationUseCase;
import dev.caskeleton.application.outbox.LegacyOutboxAppendPort;
import dev.caskeleton.application.outbox.OutboxAppendPort;
import dev.caskeleton.application.transaction.TransactionPort;
import java.time.Clock;
import org.springframework.boot.autoconfigure.AutoConfiguration;
@@ -26,27 +28,34 @@ import org.springframework.context.annotation.Import;
* <p>The use cases are beans rather than objects built inside the controller so that the method
* security advisor proxies them: {@code @RequiresPermission} on submit and cancel is enforced by
* that proxy, and a use case constructed by hand would carry the annotation and skip the check.
*
* <p>The submission event's contract is registered here as a bean, which is how the application's
* {@link IntegrationEventEncoderPort} learns it: the encoder is built over every contract
* contribution the context holds.
*/
@AutoConfiguration(
afterName =
"dev.caskeleton.adapter.outbound.persistence.autoconfigure.PersistenceJpaAutoConfiguration")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnBean({
DurableOperationStorePort.class,
LegacyOutboxAppendPort.class,
TransactionPort.class
})
@ConditionalOnBean({DurableOperationStorePort.class, OutboxAppendPort.class, TransactionPort.class})
@Import(DurableOperationController.class)
public class DurableOperationConfig {
/** The {@code durable-operation.submitted} contract, so the encoder can validate the event. */
@Bean
public DurableOperationSubmittedContract durableOperationSubmittedContract() {
return new DurableOperationSubmittedContract();
}
/** Accepts work: the operation row and its outbox event in one transaction. */
@Bean
public SubmitDurableOperationUseCase submitDurableOperationUseCase(
DurableOperationStorePort operations,
LegacyOutboxAppendPort outbox,
OutboxAppendPort outbox,
IntegrationEventEncoderPort encoder,
TransactionPort transactions,
Clock clock) {
return new SubmitDurableOperationUseCase(operations, outbox, transactions, clock);
return new SubmitDurableOperationUseCase(operations, outbox, encoder, transactions, clock);
}
/** Reads one operation for the caller that submitted it. */
@@ -1,61 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.outbox;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import java.util.Objects;
import org.springframework.beans.factory.InitializingBean;
/**
* Fail-closed activation guard for the transport-only canonical outbox path.
*
* <p>Turning on canonical transport without a canonical publisher would let the legacy relay claim
* a canonical row and then spend its retry budget against a disabled transport. The flag therefore
* requires the application-owned canonical publish port at startup.
*/
public final class OutboxCanonicalTransportRequirementValidator implements InitializingBean {
private static final String CANONICAL_KEY = "ca-skeleton.outbox.canonical-transport-enabled";
private final OutboxSettings settings;
private final IntegrationEventPublishPort publisher;
private final IntegrationEventEncoderPort encoder;
public OutboxCanonicalTransportRequirementValidator(
OutboxSettings settings,
IntegrationEventPublishPort publisher,
IntegrationEventEncoderPort encoder) {
this.settings = Objects.requireNonNull(settings, "settings must not be null");
this.publisher = publisher;
this.encoder = encoder;
}
@Override
public void afterPropertiesSet() {
validate();
}
public void validate() {
if (!settings.canonicalTransportEnabled()) {
return;
}
if (publisher == null) {
throw StartupFailures.requiredAdapterDisabled(
CANONICAL_KEY
+ "=true requires an IntegrationEventPublishPort so canonical claimed rows cannot be "
+ "consumed by the relay without a platform publication route. Configure the canonical "
+ "messaging bridge (including app.messaging.producer-id) or set "
+ CANONICAL_KEY
+ "=false.");
}
if (encoder == null) {
throw StartupFailures.requiredAdapterDisabled(
CANONICAL_KEY
+ "=true also requires an IntegrationEventEncoderPort bean. The template ships no "
+ "implementation: the adopter owns its event contracts and must provide the "
+ "encoder as part of the application messaging composition, or set "
+ CANONICAL_KEY
+ "=false.");
}
}
}
@@ -1,117 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.outbox;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
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.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
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. See README for the design rationale.
*
* <p>Application composition, like the idempotency executor: it wires application-core ports into a
* use case and drives it on a timer, which is why it stays in the composition root rather than in
* the persistence module — a driven adapter must not construct or call use cases. It names no
* module type, only ports, and it 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)
@EnableConfigurationProperties(OutboxSettings.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 OutboxConfig {
/** Requires the canonical messaging bridge whenever canonical outbox transport is enabled. */
@Bean
public OutboxCanonicalTransportRequirementValidator outboxCanonicalTransportRequirementValidator(
OutboxSettings settings,
ObjectProvider<IntegrationEventPublishPort> canonicalPublisherProvider,
ObjectProvider<IntegrationEventEncoderPort> encoderProvider) {
return new OutboxCanonicalTransportRequirementValidator(
settings, canonicalPublisherProvider.getIfAvailable(), encoderProvider.getIfAvailable());
}
/** 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. See
* README for the design rationale.
*/
@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);
}
}
@@ -1,21 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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}";
}
}
@@ -1,118 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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);
}
}
}
@@ -1,61 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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);
}
}
}
@@ -1,78 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.outbox;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;
/**
* Outbox relay runtime knobs bound from {@code ca-skeleton.outbox.*} (literal defaults, no env
* placeholders). See README for the design rationale.
*
* @param relayEnabled whether the relay scheduler is enabled; default {@code false}
* @param canonicalTransportEnabled whether canonical rows may use the platform transport; 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}
*/
@Validated
@ConfigurationProperties(prefix = "ca-skeleton.outbox")
public record OutboxSettings(
Boolean relayEnabled,
Boolean canonicalTransportEnabled,
Duration pollInterval,
Integer batchSize,
Duration inFlightTimeout,
Duration reaperInterval,
Duration publishedRetention) {
public OutboxSettings {
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;
}
if (canonicalTransportEnabled == null) {
canonicalTransportEnabled = false;
}
if (pollInterval == null) {
pollInterval = Duration.ofSeconds(5);
} else if (pollInterval.isZero() || pollInterval.isNegative()) {
throw StartupFailures.envValidation(
"ca-skeleton.outbox.pollInterval must be positive, was " + pollInterval);
}
if (batchSize == null) {
batchSize = 20;
} else if (batchSize <= 0) {
throw StartupFailures.envValidation(
"ca-skeleton.outbox.batchSize must be > 0, was " + batchSize);
}
if (inFlightTimeout == null) {
inFlightTimeout = Duration.ofMinutes(5);
} else if (inFlightTimeout.isZero() || inFlightTimeout.isNegative()) {
throw StartupFailures.envValidation(
"ca-skeleton.outbox.inFlightTimeout must be positive, was " + inFlightTimeout);
}
if (reaperInterval == null) {
reaperInterval = Duration.ofMinutes(10);
} else if (reaperInterval.isZero() || reaperInterval.isNegative()) {
throw StartupFailures.envValidation(
"ca-skeleton.outbox.reaperInterval must be positive, was " + reaperInterval);
}
if (publishedRetention == null) {
publishedRetention = Duration.ofDays(7);
} else if (publishedRetention.isZero() || publishedRetention.isNegative()) {
throw StartupFailures.envValidation(
"ca-skeleton.outbox.publishedRetention must be positive, was " + publishedRetention);
}
}
}
@@ -1,30 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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);
}
}
}
@@ -1,102 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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) {}
}
@@ -1,58 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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;
};
}
}
@@ -1,49 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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;
}
}
@@ -1,38 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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);
}
}
}
@@ -1,100 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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);
}
}
}
@@ -1,20 +0,0 @@
package dev.caskeleton.bootstrap.concurrency;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* 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.
*/
@Configuration
public class DomainContextConfig {
@Bean
public DomainContextPropagator domainContextPropagator() {
return new ThreadLocalDomainContextPropagator();
}
}
@@ -1,25 +0,0 @@
package dev.caskeleton.bootstrap.logging;
import dev.caskeleton.adapter.outbound.identifier.HmacUserPrincipalPseudonymizer;
import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort;
import dev.caskeleton.bootstrap.settings.PrivacySettings;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Composition-root wiring for {@code user_principal} pseudonymization.
* {@code @ConditionalOnMissingBean} lets a forking project substitute its own pseudonymizer. See
* README for the design rationale.
*/
@Configuration
@EnableConfigurationProperties(PrivacySettings.class)
public class PseudonymizationConfig {
@Bean
@ConditionalOnMissingBean
UserPrincipalPseudonymizerPort userPrincipalPseudonymizer(PrivacySettings privacySettings) {
return new HmacUserPrincipalPseudonymizer(privacySettings.saltBytes());
}
}
@@ -1,40 +0,0 @@
package dev.caskeleton.bootstrap.management.security;
import org.springframework.boot.security.autoconfigure.actuate.web.servlet.EndpointRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.
*/
@Configuration
public class ManagementSecurityConfig {
@Bean
@Order(0)
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();
}
}
@@ -1,31 +0,0 @@
package dev.caskeleton.bootstrap.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;
}
}
@@ -1,52 +0,0 @@
package dev.caskeleton.bootstrap.metrics;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/**
* 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
*/
@Configuration
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());
}
}
@@ -1,48 +0,0 @@
package dev.caskeleton.bootstrap.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);
}
}
@@ -1,33 +0,0 @@
package dev.caskeleton.bootstrap.settings;
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);
}
}
@@ -1,6 +1,5 @@
org.springframework.boot.EnvironmentPostProcessor=\
dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator,\
dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingEnvironmentPostProcessor
dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator
org.springframework.boot.SpringBootExceptionReporter=\
dev.caskeleton.bootstrap.runtime.startup.StartupFailureExceptionReporter
@@ -1,5 +1,2 @@
dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration
dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig
dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig
dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig
dev.caskeleton.bootstrap.autoconfigure.tracing.TracingConfig
@@ -88,6 +88,5 @@ spring:
import:
- classpath:config/server.yml
- classpath:config/observability.yml
- classpath:config/capabilities.yml
- classpath:config/runtime.yml
- classpath:config/security.yml
@@ -1,18 +0,0 @@
# 멱등성 제공자 선택과 수명 정책. Redis 역할(cache/rate-limit/lease)과 Redis 저장소 튜닝은
# cache-redis 모듈이 config/module-defaults/cache-redis.yml 로 가져온다.
#
# application.yml 이 spring.config.import 로 취합한다. 이 파일의 값은 application.yml 보다
# 낮고 application-{profile}.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.
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
@@ -44,7 +44,13 @@ class DefaultCompositionBootTest {
"dev.caskeleton.adapter.inbound.graphql",
"dev.caskeleton.adapter.inbound.websocket",
"dev.caskeleton.adapter.inbound.grpc",
"dev.caskeleton.composition");
// composition:service-runtime (`composition.runtime`) is part of the default composition;
// the outbox relay and idempotency modules are selected but build nothing until their
// store or provider is there.
"dev.caskeleton.composition.fileserver",
"dev.caskeleton.composition.notification",
"dev.caskeleton.composition.outbox",
"dev.caskeleton.composition.idempotency");
/** Infrastructure a capability connects to; a bean of any of these would open a connection. */
private static final List<String> INFRASTRUCTURE_TYPES =
@@ -2,17 +2,14 @@ package dev.caskeleton.bootstrap.autoconfigure.common;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Arrays;
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.context.annotation.Bean;
class BootstrapClockAutoConfigurationTest {
@@ -38,14 +35,6 @@ class BootstrapClockAutoConfigurationTest {
});
}
@Test
void idempotencyCompositionDoesNotOwnTheApplicationClock() {
assertThat(Arrays.stream(IdempotencyProviderSelectionConfig.class.getDeclaredMethods()))
.noneMatch(
method ->
method.getReturnType() == Clock.class && method.isAnnotationPresent(Bean.class));
}
@Test
void anAdopterClockWinsOverTheDefault() throws Exception {
Clock adopterClock = Clock.fixed(Instant.parse("2026-09-18T00:00:00Z"), ZoneOffset.UTC);
@@ -1,116 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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 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.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 IdempotencyProviderCompositionTest {
private static final String POSTGRESQL_STORE_CONFIG =
"dev.caskeleton.adapter.outbound.persistence.autoconfigure.PostgreSqlIdempotencyStoreConfig";
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(IdempotencyProviderSelectionConfig.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"));
}
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.postgresql.idempotency")
static class ScannedPersistence {}
}
@@ -1,147 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class IdempotencySettingsTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner().withUserConfiguration(Binding.class);
@Test
void absentKeysBindToTheDocumentedDefaults() {
runner.run(
context ->
assertThat(context.getBean(IdempotencySettings.class))
.usingRecursiveComparison()
.isEqualTo(
new IdempotencySettings(
IdempotencySettings.Provider.DISABLED,
Duration.ofSeconds(30),
Duration.ofHours(24),
Duration.ofHours(24),
"json-v2",
2,
Duration.ofMinutes(10))));
}
@Test
void kebabCaseKeysBindEveryField() {
runner
.withPropertyValues(
"ca-skeleton.capabilities.idempotency.provider=postgresql",
"ca-skeleton.capabilities.idempotency.processing-lease=45s",
"ca-skeleton.capabilities.idempotency.replay-ttl=72h",
"ca-skeleton.capabilities.idempotency.failure-retention=2h",
"ca-skeleton.capabilities.idempotency.response-codec-id=json-v3",
"ca-skeleton.capabilities.idempotency.policy-revision=3",
"ca-skeleton.capabilities.idempotency.reaper-interval=1m")
.run(
context ->
assertThat(context.getBean(IdempotencySettings.class))
.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() {
runner
.withPropertyValues("ca-skeleton.capabilities.idempotency.provider=jdbc")
.run(
context ->
assertThat(context)
.hasFailed()
.getFailure()
.hasStackTraceContaining("ca-skeleton.capabilities.idempotency.provider"));
}
@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");
}
@EnableConfigurationProperties(IdempotencySettings.class)
static class Binding {}
}
@@ -1,76 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.outbox;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
import dev.caskeleton.application.outbox.OutboxStorePort;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
class OutboxCanonicalTransportCompositionTest {
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withUserConfiguration(OutboxConfig.class)
.withBean(OutboxStorePort.class, () -> mock(OutboxStorePort.class))
.withPropertyValues(
"ca-skeleton.outbox.enabled=true", "ca-skeleton.outbox.relay-enabled=false");
@Test
void defaultCanonicalTransportOffStartsWithoutCanonicalPublisher() {
runner.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).hasSingleBean(OutboxCanonicalTransportRequirementValidator.class);
assertThat(context).doesNotHaveBean(IntegrationEventPublishPort.class);
});
}
@Test
void canonicalTransportOnWithoutPublisherFailsTheComposedContext() {
runner
.withPropertyValues("ca-skeleton.outbox.canonical-transport-enabled=true")
.run(
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.hasMessageContaining("IntegrationEventPublishPort");
});
}
@Test
void canonicalTransportOnWithPublisherButWithoutEncoderFailsClosed() {
runner
.withPropertyValues("ca-skeleton.outbox.canonical-transport-enabled=true")
.withBean(
IntegrationEventPublishPort.class,
() -> event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED))
.run(
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.hasMessageContaining("IntegrationEventEncoderPort");
});
}
@Test
void canonicalTransportOnWithPublisherAndEncoderStartsWithoutCreatingAnotherScheduler() {
runner
.withPropertyValues("ca-skeleton.outbox.canonical-transport-enabled=true")
.withBean(
IntegrationEventPublishPort.class,
() -> event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED))
.withBean(IntegrationEventEncoderPort.class, () -> draft -> null)
.run(
context -> {
assertThat(context).hasNotFailed();
assertThat(context).hasSingleBean(IntegrationEventPublishPort.class);
assertThat(context).hasSingleBean(IntegrationEventEncoderPort.class);
assertThat(context).doesNotHaveBean(OutboxRelayScheduler.class);
});
}
}
@@ -1,59 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.outbox;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
import java.util.concurrent.CompletableFuture;
import org.junit.jupiter.api.Test;
class OutboxCanonicalTransportRequirementValidatorTest {
@Test
void enabledCanonicalTransportWithoutPublisherFailsStartup() {
OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null);
assertThatThrownBy(
() -> new OutboxCanonicalTransportRequirementValidator(settings, null, null).validate())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("canonical-transport-enabled")
.hasMessageContaining("IntegrationEventPublishPort");
}
@Test
void disabledCanonicalTransportDoesNotRequirePublisher() {
OutboxSettings settings = new OutboxSettings(true, false, null, null, null, null, null);
assertThatCode(
() -> new OutboxCanonicalTransportRequirementValidator(settings, null, null).validate())
.doesNotThrowAnyException();
}
@Test
void enabledCanonicalTransportWithPublisherButWithoutEncoderFailsStartup() {
OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null);
IntegrationEventPublishPort publisher =
event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED);
assertThatThrownBy(
() ->
new OutboxCanonicalTransportRequirementValidator(settings, publisher, null)
.validate())
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("IntegrationEventEncoderPort");
}
@Test
void enabledCanonicalTransportWithPublisherStarts() {
OutboxSettings settings = new OutboxSettings(true, true, null, null, null, null, null);
IntegrationEventPublishPort publisher =
event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED);
assertThatCode(
() ->
new OutboxCanonicalTransportRequirementValidator(settings, publisher, draft -> null)
.validate())
.doesNotThrowAnyException();
}
}
@@ -1,106 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.scheduling.config.TaskManagementConfigUtils;
class OutboxConfigTest {
@Test
void outboxRandomGeneratorIsAvailableInTheSlimJavaBaseRuntime() {
RandomGenerator random = new OutboxConfig().outboxRandomGenerator();
assertThat(random.getClass().getModule().getName()).isEqualTo("java.base");
}
@Test
void outboxCapabilityEnablesSchedulingWithIdempotencyDisabled() {
// given
ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(OutboxConfig.class))
.withBean(OutboxStorePort.class, OutboxConfigTest::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(OutboxConfig.class))
.withBean(OutboxStorePort.class, OutboxConfigTest::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(OutboxConfig.class))
.withBean(OutboxStorePort.class, OutboxConfigTest::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(OutboxConfig.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());
});
}
}
@@ -1,76 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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();
}
}
}
@@ -1,122 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.outbox;
import static org.assertj.core.api.Assertions.assertThat;
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 java.time.Duration;
import org.junit.jupiter.api.Test;
/**
* Binding and validation tests for {@link OutboxSettings} (feature-domain-event-outbox-contract I11
* — mirrors IdempotencyPropertiesTest).
*/
class OutboxSettingsTest {
@Test
void bindsAllSixDefaultsWhenFieldsAreNull() {
OutboxSettings props = new OutboxSettings(null, null, null, null, null, null, null);
assertThat(props.relayEnabled()).isFalse();
assertThat(props.canonicalTransportEnabled()).isFalse();
assertThat(props.pollInterval()).isEqualTo(Duration.ofSeconds(5));
assertThat(props.batchSize()).isEqualTo(20);
assertThat(props.inFlightTimeout()).isEqualTo(Duration.ofMinutes(5));
assertThat(props.reaperInterval()).isEqualTo(Duration.ofMinutes(10));
assertThat(props.publishedRetention()).isEqualTo(Duration.ofDays(7));
}
@Test
void acceptsExplicitValidValues() {
OutboxSettings props =
new OutboxSettings(
false,
true,
Duration.ofSeconds(10),
50,
Duration.ofMinutes(2),
Duration.ofHours(1),
Duration.ofDays(14));
assertThat(props.relayEnabled()).isFalse();
assertThat(props.canonicalTransportEnabled()).isTrue();
assertThat(props.pollInterval()).isEqualTo(Duration.ofSeconds(10));
assertThat(props.batchSize()).isEqualTo(50);
assertThat(props.inFlightTimeout()).isEqualTo(Duration.ofMinutes(2));
assertThat(props.reaperInterval()).isEqualTo(Duration.ofHours(1));
assertThat(props.publishedRetention()).isEqualTo(Duration.ofDays(14));
}
@Test
void rejectsZeroBatchSize() {
assertThatThrownBy(() -> new OutboxSettings(true, false, null, 0, null, null, null))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("batchSize");
}
@Test
void rejectsNegativeBatchSize() {
assertThatThrownBy(() -> new OutboxSettings(true, false, null, -1, null, null, null))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("batchSize");
}
@Test
void rejectsNonPositivePollInterval() {
assertThatThrownBy(() -> new OutboxSettings(true, false, Duration.ZERO, null, null, null, null))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("pollInterval");
}
@Test
void rejectsNonPositiveInFlightTimeout() {
assertThatThrownBy(() -> new OutboxSettings(true, false, null, null, Duration.ZERO, null, null))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("inFlightTimeout");
}
@Test
void rejectsZeroReaperInterval() {
assertThatThrownBy(() -> new OutboxSettings(true, false, null, null, null, Duration.ZERO, null))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("reaperInterval");
}
@Test
void rejectsNegativeReaperInterval() {
assertThatThrownBy(
() -> new OutboxSettings(true, false, null, null, null, Duration.ofMinutes(-1), null))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("reaperInterval");
}
@Test
void rejectsZeroPublishedRetention() {
assertThatThrownBy(() -> new OutboxSettings(true, false, null, null, null, null, Duration.ZERO))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("publishedRetention");
}
@Test
void rejectsNegativePublishedRetention() {
assertThatThrownBy(
() -> new OutboxSettings(true, false, null, null, null, null, Duration.ofHours(-1)))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("publishedRetention");
}
}
@@ -1,56 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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
}
}
@@ -1,92 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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);
}
}
@@ -1,59 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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");
}
}
@@ -1,214 +0,0 @@
package dev.caskeleton.bootstrap.autoconfigure.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 {}
}
@@ -6,7 +6,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration;
import dev.caskeleton.bootstrap.management.security.ManagementSecurityConfig;
import dev.caskeleton.composition.runtime.management.security.ManagementSecurityConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -17,7 +17,7 @@ import org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration;
import org.springframework.boot.jdbc.autoconfigure.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.test.web.servlet.MockMvc;
/**
@@ -109,6 +109,9 @@ class ActuatorSecurityHttpTest {
WebAdapterAutoConfiguration.class,
WebSecurityAutoConfiguration.class
})
@Import(ManagementSecurityConfig.class)
// The web adapter's SecurityConfig is what enables web security in the shipped composition;
// with it excluded, the slice enables it itself so composition:service-runtime's
// ManagementSecurityConfig arrives the way it does in production — as an auto-configuration.
@EnableWebSecurity
static class MinimalActuatorApp {}
}
@@ -22,12 +22,11 @@ class BootstrapCapabilityAutoConfigurationReachabilityTest {
// Redis and the distributed lock are no longer here. Each moved into the module that
// implements it — `adapter:outbound:cache-redis` (with its readiness append and
// activation guard) and `adapter:outbound:persistence-jpa` — which ships its own
// registration and its own reachability test. The outbox relay stays: it assembles a use
// case over ports, which is composition, and it turns on from the store port the
// persistence module contributes.
"dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig",
"dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig",
"dev.caskeleton.bootstrap.autoconfigure.tracing.TracingConfig");
// registration and its own reachability test. So did the outbox relay and the
// idempotency executor: `composition:outbox-relay` and `composition:idempotency`, which
// the sample composes too. Tracing, metrics, domain context, pseudonymization and the
// actuator chain are `composition:service-runtime`, which proves its own registration.
"dev.caskeleton.bootstrap.autoconfigure.operation.DurableOperationConfig");
@Test
void everyBootstrapOwnedCapabilityRootIsDiscoverableByBoot() {
@@ -84,14 +84,10 @@ class ConfigurationNamespaceContractTest {
List.of(
"ca-skeleton.async.executor",
"ca-skeleton.bootstrap",
"ca-skeleton.capabilities.idempotency",
"ca-skeleton.logging",
"ca-skeleton.outbox",
"ca-skeleton.privacy",
"ca-skeleton.runtime",
"ca-skeleton.secret-source",
"ca-skeleton.security",
"ca-skeleton.tracing"));
"ca-skeleton.security"));
private static final Pattern PREFIX_ANNOTATION =
Pattern.compile("@ConfigurationProperties\\(\\s*(?:prefix\\s*=\\s*)?\"([^\"]+)\"");
@@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.observability.MdcKeys;
import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory;
import dev.caskeleton.bootstrap.async.AsyncContextTaskDecorator;
import dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingRateGauge;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.composition.runtime.tracing.TracingSamplingRateGauge;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import dev.caskeleton.shared.response.ResponseMeta;
import dev.caskeleton.shared.tracing.BaggageAllowlist;
@@ -39,7 +39,7 @@ import org.yaml.snakeyaml.Yaml;
* dev.caskeleton.bootstrap.autoconfigure.tracing.TracingPropertiesTest}
* <li>{@code tracing-contract:meta-traceid-when-disabled} — this class
* <li>{@code tracing-contract:sample-rate-per-profile} — see {@link
* dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSampleRateResolverTest}
* dev.caskeleton.composition.runtime.tracing.TracingSampleRateResolverTest}
* <li>{@code contract-verification:trace-propagation} — this class
* <li>{@code contract-verification:metrics-cardinality} — this class
* <li>{@code contract-verification:log-mdc-keys} — this class
@@ -3,8 +3,8 @@ package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
import dev.caskeleton.bootstrap.metrics.MetricsContractConfig;
import dev.caskeleton.bootstrap.metrics.MetricsDistributionMeterFilter;
import dev.caskeleton.composition.runtime.metrics.MetricsContractConfig;
import dev.caskeleton.composition.runtime.metrics.MetricsDistributionMeterFilter;
import dev.caskeleton.shared.metrics.AlertSeverity;
import dev.caskeleton.shared.metrics.CardinalityBounds;
import dev.caskeleton.shared.metrics.ForbiddenMetricTags;
@@ -1,9 +1,12 @@
package dev.caskeleton.bootstrap.autoconfigure.tracing;
package dev.caskeleton.bootstrap.contract;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration;
import dev.caskeleton.composition.runtime.tracing.MicrometerSpanErrorRecorder;
import dev.caskeleton.composition.runtime.tracing.TracingConfig;
import dev.caskeleton.composition.runtime.tracing.TracingSamplingRateGauge;
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.tracing.Tracer;
@@ -16,10 +16,10 @@ import org.junit.jupiter.api.Test;
* How many things own {@code app.messaging}, and how many can publish one event (MSG-INT-002).
*
* <p>Two types declare {@code @ConfigurationProperties} on that prefix: {@code MessagingSettings}
* in the outbound adapter, which owns {@code broker}, and {@code MessagingSettings} in the starter,
* which owns everything else. Spring binds both without complaint — each takes the fields it
* declares — so the split is invisible at runtime and shows up only as two places to look, neither
* of which validates the other's view.
* in the outbound adapter, which owns {@code producer-id}, and {@code MessagingSettings} in the
* starter, which owns everything else, {@code broker} included. Spring binds both without complaint
* — each takes the fields it declares — so the split is invisible at runtime and shows up only as
* two places to look, neither of which validates the other's view.
*
* <p>This test does not assert the split away. Collapsing it means the adapter stops selecting a
* broker and becomes a port bridge over the platform's publish contract, which it can only do once
@@ -102,8 +102,8 @@ class MessagingAuthorityContractTest {
assertThat(leaks)
.as(
"MessagePublisher in the adapter is an adapter-local type; if general publish ever "
+ "becomes a use-case need, an application port is defined first")
"the messaging adapter's types are adapter-local; if a use case ever needs to "
+ "publish, an application port is defined first")
.isEmpty();
}
@@ -1,54 +0,0 @@
package dev.caskeleton.bootstrap.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}");
});
}
}
@@ -1,146 +0,0 @@
package dev.caskeleton.bootstrap.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();
}
}
@@ -1,121 +0,0 @@
package dev.caskeleton.bootstrap.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();
}
}
@@ -1,154 +0,0 @@
package dev.caskeleton.bootstrap.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);
}
}
@@ -16,7 +16,7 @@ import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfi
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings;
import dev.caskeleton.bootstrap.CaSkeletonApplication;
import dev.caskeleton.bootstrap.logging.PseudonymizationConfig;
import dev.caskeleton.composition.runtime.logging.PseudonymizationConfig;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -3,7 +3,6 @@ package dev.caskeleton.bootstrap.runtime.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupOrder;
import dev.caskeleton.bootstrap.autoconfigure.tracing.TracingSamplingEnvironmentPostProcessor;
import dev.caskeleton.bootstrap.runtime.RuntimeEnvironmentProfileValidator;
import java.io.IOException;
import java.io.InputStream;
@@ -20,11 +19,12 @@ class StartupOrderContractTest {
@Test
void everyRegisteredEnvironmentPostProcessorHasTheExpectedCentralOrder() throws Exception {
// The tracing sampling bridge is composition:service-runtime's registration now; that module
// pins its StartupOrder position itself.
Map<String, Integer> expected =
Map.of(
RuntimeEnvironmentProfileValidator.class.getName(),
StartupOrder.RUNTIME_ENVIRONMENT_PROFILE,
TracingSamplingEnvironmentPostProcessor.class.getName(), StartupOrder.TRACING_SAMPLING);
StartupOrder.RUNTIME_ENVIRONMENT_PROFILE);
Map<String, Integer> actual = registeredEnvironmentPostProcessorOrders();
@@ -1,91 +0,0 @@
package dev.caskeleton.bootstrap.settings;
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 {}
}