review-followup Wave 3 라운드 2(P25): core 죽은 표면·web·GraphQL·WebSocket·sample 구조, 소유자 결정 32 기록

- 삭제: core 죽은 계약 타입·opstore·rate-limit disabled·GraphQL 병렬 HTTP envelope·sample legacy 포스터 업로드 모드
- durable operation이 `CommandUseCase` 구현, 알림 템플릿 버전·locale 기본값을 설정으로(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`=ko-KR),
  `GraphQlPlatformAutoConfiguration` 기능별 분해, STOMP broker executor, startup 예외 하나, profile reader ArchUnit 확대
- web 보안 root 분리, sample scan을 sample 패키지로(NEW-10d·S6-#8 — 새 web controller가 sample에 등록되지 않음)
- sample 정렬 이름·요청 파싱 helper·게시 파라미터 record·reconcile은 명시 명령(P14-new-3)
- 통합: P24와 겹친 sample 포스터 설정은 P24 쪽(`PosterImageApiSettings` DISABLED/PUBLICATION 검증) 유지
- 현황표: 소유자 결정 32(fileserver 권한 추가), S1-#6b·S1-#18b·S6-#10a를 P28로

검증: ./gradlew check architectureCheck verifyDependencyLocks verifyPublicPathSnapshot :app-bootstrap:verifyEnvKeys
:sample-portfolio:integrationTest :sample-portfolio:systemTest :app-bootstrap:integrationTest --continue 통과(657 task)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
donghyeon-ka
2026-09-28 17:33:10 +09:00
co-authored by Claude Opus 5.5
parent 64a8391889
commit 25de288ab4
169 changed files with 2410 additions and 2257 deletions
+1 -3
View File
@@ -5,7 +5,7 @@
# split into capability artifacts.
# Update only after review with:
# ./gradlew :adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange
# types: 163
# types: 161
dev.caskeleton.adapter.inbound.graphql.HealthGraphqlController
dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile
dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationId
@@ -89,10 +89,8 @@ dev.caskeleton.adapter.inbound.graphql.fetch.GraphQlUnmappedSelectionException
dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy
dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpContractException
dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpOutcome
dev.caskeleton.adapter.inbound.graphql.http.GraphQlHttpRequestEnvelope
dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy
dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonValues
dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestEnvelopeValidator
dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestFormatException
dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestSize
dev.caskeleton.adapter.inbound.graphql.http.GraphQlRequestTooLargeException
+8
View File
@@ -414,3 +414,11 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap
| 예외 서브클래스 17개(`AtomicPublishUnsupported`·`ConcurrentFileModification`·`FileAccessDenied`·`FileNotReady`·`FileTooLarge`·`IntegrityMismatch`·`MalformedRequest`·`MalwareDetected`·`PartialWrite`·`PathOutsideNamespace`·`QuotaExceeded`·`StorageFull`·`StorageUnavailable`·`TransferAdmissionRejected`·`TransferTimeout`·`UnsupportedMediaType`·`UploadExpired` + `Exception`) | `src/application-fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/` | `c4a066df` | 타입 분기 0, code가 같은 정보(S1-#7) |
| `FileserverWebProperties.defaultNamespace`·`uploadTtl`, `TusProperties.uploadTtl`, `Draft12Properties.uploadTtl` | `src/adapter/inbound/web-fileserver/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver/` | `c4a066df` | 업로드 세션 정책이 `UploadPolicy`로(S5-#10). 설정 키 변화 없음 |
| `ObjectRequestSupport.boundedToken` | `src/application-objectstorage/src/main/java/dev/caskeleton/application/objectstorage/request/ObjectRequestSupport.java` | `c4a066df` | `ObjectModelSupport.requireBoundedToken`과 중복(S1-#17a) |
| `RedisHealthSnapshotProvider` | `src/shared-contract/src/main/java/dev/caskeleton/shared/health/RedisHealthSnapshotProvider.java` | `4fb7943b` | 구현·소비자 0 (A-5b) |
| `opstore` 패키지(`OperationalRecordStorePort`·`OperationalRecord`·`OperationalRecordConflictException`) | `src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/` | `4fb7943b` | 사용처 0 (X1-#6f, S1-#15b, NEW-9b) |
| `DomainContextStrategy`·`DomainContextPropagatorFactory` + 테스트 | `src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/` | `4fb7943b` | case 하나뿐인 확장 지점 (A-10c) |
| `DomainContextSettings`(`ca-skeleton.domain-context.strategy`) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextSettings.java` | `4fb7943b` | 선택할 전략이 하나 (A-10c) |
| `RateLimitInterceptor.disabled` + 테스트 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptor.java` | `4fb7943b` | M2 이후 dead (I-8d) |
| `GraphQlRequestEnvelopeValidator`·`GraphQlHttpRequestEnvelope` + `GraphQlRequestEnvelopeValidatorTest` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/` | `4fb7943b` | 요청 경로에서 도달 불가 (J-10d) |
| `MigrationFailedException`·`ProfileMismatchException`·`RequiredAdapterDisabledException`·`StartupValidationException` | `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/` | `f2857840^`(= `b7187e1b`) | 역할 없는 subclass (S6-#13) |
| `ExternalRequestUrlResolver`의 forwarded 파싱 + env `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | `src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java` | `d54909c4` | 컨테이너(RemoteIpValve)와 다른 두 번째 신뢰 판단 (I-5b) |
+15 -15
View File
@@ -4231,6 +4231,21 @@ env_keys:
compatibility_impact: behavior-change
required_test: adapter-contract:notification-platform-disabled-safe
- name: APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE
# I-6b: the locale a submission that names none is rendered in. The accept use case applies
# it; the HTTP controller used to pick the host JVM's Locale.getDefault(), so the same request
# rendered differently per node.
type: string
default: ko-KR
allowed_values: null
classification: public-config
required: false
reload_policy: restart-only
owner_branch: worktree-notification-platform
validation: none
compatibility_impact: behavior-change
required_test: application-contract:notification-default-locale
- name: APP_NOTIFICATION_PLATFORM_CONTACT_ENCRYPTION_KEY
# source: NTF-INT-007 — Encrypts recipient contact points at rest — addresses and phone numbers.
# Full row owned by secrets-classification.yaml. Bound by
@@ -5178,21 +5193,6 @@ env_keys:
compatibility_impact: behavior-change
required_test: adapter-contract:notification-callback-body-bound
- name: APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES
# source: NTF-001 — peers whose forwarded headers may be believed when reconstructing the URL a
# provider signed. Empty means the resolver uses what the container observed; honouring
# forwarded headers unconditionally would let any caller pick the URL its signature is checked
# against, which defeats the signature.
type: csv
default: ""
allowed_values: null
classification: security-relevant
required: false
reload_policy: restart-only
owner_branch: worktree-notification-platform
validation: none
compatibility_impact: behavior-change
required_test: adapter-contract:notification-callback-url-resolution
- name: APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW
# source: NTF-025 — how far a callback timestamp may differ from local time before it is treated as a replay
type: duration
@@ -0,0 +1,70 @@
# W3-P25 — core 죽은 표면 · web · GraphQL · WebSocket · sample 구조
worktree `.claude/worktrees/agent-aaeb73c00f4ac3d5d`, 브랜치 `worktree-agent-aaeb73c00f4ac3d5d`, 기준 `4fb7943b`.
커밋:
- `d54909c4` review-followup P25 D: 죽은 core 표면·rate-limit disabled·GraphQL 병렬 envelope·sample legacy 포스터 업로드 삭제
- `b7187e1b` review-followup P25 W3: durable operation CommandUseCase·callback URL·알림 기본값·GraphQL 조립 분해·STOMP broker executor
- `f2857840` review-followup P25 W3: startup 예외 하나로·profile reader ArchUnit 확대·bootstrap.autoconfigure 규칙
- `68537419` review-followup P25 W3: web 보안 root 분리·sample scan을 sample 패키지로
- `7018238b` review-followup P25 W3: sample 정렬 이름·요청 파싱 helper·게시 파라미터 record·reconcile 명령 경로
## 행 결과
| ID | 결과 | 근거 |
|---|---|---|
| A-2c | 완료 | `RuntimeProfileAccessArchitectureTest`를 `@AnalyzeClasses(packages = "dev.caskeleton")`, `resideOutsideOfPackages(messaging.., sample..)`로 넓히고 허용 목록 `PROFILE_READERS`(`app-bootstrap/src/architectureTest/.../RuntimeProfileAccessArchitectureTest.java:29`)를 5곳(RuntimeProfileSnapshot, GraphQlPlatformAutoConfiguration, FileserverSecurityConfiguration, HttpClientProfileAutoConfiguration, ObjectStorageCapabilityConfig)으로 고정. 규칙이 실제로 무는지: 목록에서 graphql·objectstorage를 빼고 돌려 FAIL(`Rule 'BOOT-002: …' was violated (3 times): … GraphQlPlatformAutoConfiguration.graphQlPlatformConfigurationCheck … calls method <Environment.getActiveProfiles()>`) 확인 후 원복 → PASS |
| A-4b | 완료 | `SubmitDurableOperationUseCase implements CommandUseCase<OperationCommand, OperationAcceptance>`, `submit`→`handle`(`application-core/.../operation/SubmitDurableOperationUseCase.java:54,88`), `OperationCommand implements Command`. `SubmitDurableOperationUseCaseTest`의 필드 타입을 `CommandUseCase<…>`로 바꿔 FAIL(`type argument OperationCommand is not within bounds of type-variable C` / `SubmitDurableOperationUseCase cannot be converted to CommandUseCase`)→PASS. 호출부(`DurableOperationController`, postgresql IT) 갱신, `jpaPlatformContractTest` 217/217 |
| A-5b | 해당 없음(코드 삭제) | `d54909c4`: `shared/health/RedisHealthSnapshotProvider.java` 삭제, `shared-contract/CLAUDE.md`·`README.md` 문장 삭제 |
| A-5c | 완료 | `MetricNaming`·`CardinalityBounds`·`AlertSeverity`·`BaggageAllowlist`를 shared-contract `src/testFixtures`로 이동(`java-test-fixtures` + `gradle.lockfile` 재생성), app-bootstrap `testImplementation(testFixtures(project(':shared-contract')))`. main에는 `ForbiddenMetricTags`만 남음. README metrics 절·CLAUDE.md 책임 목록 정리. 기존 계약 테스트 그대로 PASS |
| A-10c | 해당 없음(코드 삭제) | `d54909c4`: `DomainContextStrategy`·`DomainContextPropagatorFactory`·`DomainContextSettings`(`ca-skeleton.domain-context`)·`DomainContextPropagatorFactoryTest` 삭제, `DomainContextConfig`가 `new ThreadLocalDomainContextPropagator()`. `ConfigurationNamespaceContractTest`의 prefix 목록에서 제거하고 스캔 비어있음 가드를 `hasSizeGreaterThan(10)`→`isNotEmpty()`(prefix 하나 줄어 10개가 됨) |
| I-5b | 완료 | `ExternalRequestUrlResolver`의 `Forwarded`/`X-Forwarded-*` 파싱과 trusted-proxy 목록 삭제, 컨테이너 값만 사용(`web-notification/.../callback/ExternalRequestUrlResolver.java:20`). env `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES`·설정 `…callbacks.trusted-proxies` 삭제(`env-keys.yaml`, `.env.example`, `notification.yml`, composition README). `ExternalRequestUrlResolverTest.forwardedHeadersOnTheRequestDoNotChangeTheResolvedUrl` FAIL(`expected: "http://internal.local:8080/callbacks/ses?a=1" but was: "https://attacker.example/callbacks/ses?a=1"`, trusted peer 설정 시)→PASS. `NotificationCallbackMvcControllerTest` 두 케이스 갱신 |
| I-6b | 완료 | `AcceptNotificationCommand.templateVersion`·`locale`, `PublishNotificationTemplateCommand.version`을 `Optional`로. 기본값은 유스케이스가 적용: `NotificationTemplateVersion.FIRST_VERSION`, 새 설정 `ca-skeleton.notification.platform.default-locale`(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`, 기본 `ko-KR`, ROOT 거부) — `AcceptNotificationApplicationUseCase.java:134-135`, `PublishNotificationTemplateApplicationUseCase.java:82`. 컨트롤러의 `Locale.getDefault()`·`DEFAULT_TEMPLATE_VERSION` 제거. 새 테스트 `aCommandNamingNoVersionOrLocaleGetsTheFirstVersionAndTheConfiguredLocale`, `theRootLocaleIsRefusedAsTheConfiguredDefault`, `aPublicationNamingNoVersionPublishesTheFirstVersion`(시그니처 변경이라 FAIL 단계는 컴파일 오류). 기본 locale 값 `ko-KR`은 소유자 결정 11(한국어)에 맞춘 선택 — 다르게 원하면 env 한 줄 |
| I-8d | 해당 없음(코드 삭제) | `d54909c4`: `RateLimitInterceptor.disabled`와 null-bridge 분기·`disabledModeHasNoProviderOrPseudonymizerSideEffects` 삭제, 팩토리 `enabled`는 public 생성자로 |
| J-7 | 완료 | `BoundedPreparsedDocumentProvider.expireIdle`이 첫 미만료 항목에서 `return`(`graphql/.../execution/BoundedPreparsedDocumentProvider.java:180`). 새 `aReaccessedEntryOutlivesAnOlderIdleOneEvenWhenItWasCachedFirst` PASS(성능 변경이라 동작 FAIL 재현 없음 — 순서 보존만 고정) |
| J-10d | 해당 없음(코드 삭제) | `d54909c4`: `GraphQlRequestEnvelopeValidator`·`GraphQlHttpRequestEnvelope`·`GraphQlRequestEnvelopeValidatorTest` 삭제. 한도 테스트는 실제 경로로: `runtime/GraphQlPlatformWebInterceptorRequestBoundsTest`(auto-configured interceptor로 document/variables byte·depth·미등록 extension 거부 5건), `GraphQlRequestBoundsTest`는 `GraphQlJsonValues`·`GraphQlRequestSize`·`GraphQlExtensionsPolicy` 대상. API surface 재승인(163→161) |
| K-11b | 완료 | `WebSocketConfig.configureMessageBroker`에서 `bounded(registry.configureBrokerChannel())`(`websocket/.../stomp/WebSocketConfig.java:102`) — simple broker fan-out이 발행 스레드가 아니라 bounded executor에서, 큐가 차면 broadcaster가 drop(R1). `WebSocketAutoConfigurationTest.brokerChannelFansOutOnItsOwnBoundedExecutorInsteadOfThePublishingThread` FAIL(`Expecting actual not to be null` — broker channel executor 없음)→PASS |
| X1-#6f | 해당 없음(코드 삭제) | `d54909c4`: `shared/opstore/` 3개 삭제 |
| S1-#15b | 해당 없음(코드 삭제) | `d54909c4`(X1-#6f와 같은 삭제) |
| S5-#7a | 완료 | `GraphQlPlatformAutoConfiguration`(38 bean)을 기능별 package-private `@Configuration` 8개로 분해: `GraphQlRequestContextConfiguration`·`GraphQlExecutionChainConfiguration`·`GraphQlErrorConfiguration`·`GraphQlScalarConfiguration`·`GraphQlObservationConfiguration`·`GraphQlPreparsedCacheConfiguration`·`GraphQlDataLoaderConfiguration`·`GraphQlRequestBodyLimitConfiguration`. `GraphQlPlatformAutoConfiguration`은 startup 검증 + anonymous 상수만. `GraphQlRootAutoConfiguration.java:27` `@Import`에 나열. 새 클래스는 package-private이라 API surface 변화 없음. graphql `test`·`systemTest`·`graphqlTransportQualificationTest` PASS |
| S6-#8 | 완료 | `SamplePortfolioApplication`: `@ComponentScan("dev.caskeleton.sample")`·`@ConfigurationPropertiesScan("dev.caskeleton.sample")`, 제외는 `WebSecurityAutoConfiguration` 하나(`SamplePortfolioApplication.java:31-32`). web·objectstorage는 각 auto-config로. `SamplePublicAccessSecurityConfigTest.sampleCompositionRootExcludesOnlyTheWebSecurityRoot`·`sampleCompositionRootScansOnlyTheSamplePackage`(옛 exclude-filter 단언 대체). sample `test`·`integrationTest` 51·`systemTest` 3·`webSystemTest` 5 PASS |
| S6-#10a | 남음 | 이유: 기능별 패키지 재배치와 poster-image 별도 sample 모듈 분리는 sample 전체 파일 이동(+`modules.json` leaf 등록)이라, 동시에 도는 P18(sample outbox·멱등성·`PosterEventPublisher`)·P24(object storage)와 같은 파일을 대량으로 겹친다. 통합 뒤 단독 작업으로 넘김. 이번 묶음에서 legacy 모드 삭제(S6-#10b)로 poster 표면은 줄었다 |
| S6-#10b | 해당 없음(코드 삭제) | `d54909c4`: `LegacyPosterImageController`·`UploadPosterImageUseCase`·`UploadPosterImageCommand`·`LegacyPosterImageAttachment`·`PosterImageApiConfig`·`PosterImageApiSettings`(LEGACY 모드)·`Poster.attachImage`·`Poster.imageKey()`·dual-read `rehydrate` 삭제. `PosterEntity`는 `image_key`를 매핑하지 않고, CAS attach가 `image_key = NULL`로 pre-V8 행을 정규 경로로 받는다(`PosterImageAttachmentCasRepository.java:32`). `PosterRepositoryAdapterIntegrationTest.aPreV8RawKeyRowReadsBackWithoutAnImage`·`canonicalAttachClearsAPreV8RawKeyOnTheSameRow` PASS(삭제에 따른 새 동작이라 FAIL 재현 없음). `PosterResponse.imageKey` wire 이름은 유지하고 published reference를 싣는다. sample `local` 프로필·systemTest yml의 `mode: legacy`·`object-storage.legacy` 블록 삭제 |
| S6-#10c | 완료(부분 수정 방향 변경) | `PublishPosterImageUseCase` 설정값 인자(destination·epoch·intentTtl·handoffLease)를 `PosterImagePublicationParameters` record 하나로(생성자 14→11, 양수 검증). 상태 머신(`PosterImageUploadIntent`)의 domain 이동은 하지 않음: 필드가 `application-objectstorage`·`application-core` 값 타입(`ObjectOperationKey`, `ObjectStageHandle`, `ObjectVersionToken`, `ObjectContentIdentity`, `ObjectMediaType`, `RequestFingerprint`)이라 domain으로 옮기면 domain→application 의존이 생긴다(HARD-STOP 1과 같은 방향 위반). sample `test` PASS |
| S6-#10d | 완료 | `WorkLogSortField`·`PosterSortField`는 논리 필드만. 요청 이름은 web mapper `SORT_FIELDS`(`WorkLogWebMapper.java:24`, `PosterWebMapper.java:19`), persistence 속성은 `sortProperty`(`WorkLogPersistenceMapper.java:57`, `PosterPersistenceMapper.java:38`). 계약 테스트·integration 51 PASS |
| S6-#11a | 완료 | `WebRequestParams`(`canonicalUuid`, `sort`) 하나로 `toId` 3벌(legacy 컨트롤러는 삭제)·sort 파싱 2벌 대체. `WebRequestParamsTest` 4건 PASS(대소문자 무시 매칭, `SORT_FIELD_NOT_ALLOWED` + 메시지, 빈 값, UUID 정규화) |
| S6-#13 | 완료 | 4개 subclass 삭제, `StartupFailureException`을 final + package-private 생성자로(`support/.../startup/StartupFailureException.java:18,25`), 생성은 `StartupFailures`만. 테스트 23개 파일의 `isInstanceOf(XxxException.class)`를 `isInstanceOfSatisfying(StartupFailureException.class, e -> errorCode 단언)`으로. `StartupFailureExceptionTest`는 코드→exit 파라미터 테스트. support·persistence-jpa·cache-redis·app-bootstrap `test`/`architectureTest` PASS |
| NEW-9b | 해당 없음(코드 삭제) | `d54909c4`(opstore 삭제). `docs/study/graphql-walkthrough.ko.md` 언급은 NEW-14에서 |
| NEW-10d | 완료 | `WebAdapterAutoConfiguration`(envelope·filter·health·rate limit)과 새 `WebSecurityAutoConfiguration`(JwtDecoderConfig·SecurityConfig·MethodSecurityConfig·RedisSessionWebConfig·JwtToAuthenticatedPrincipalConverter·AuthorizationAdapter·RolePermissionRegistry + 보안 settings)으로 분리, 둘 다 imports 등록(`WebAutoConfigurationRegistrationTest` 목록 추가). sample webSystemTest 4곳·sample slice 테스트의 문자열 `excludeName`을 클래스 참조로. fixture 앱 2개(`ContractFixtureApplication`·`PipelineOrderFixtureApplication`)는 core root가 RequestLoggingFilter(pseudonymizer 필요)를 가져오므로 두 root를 클래스로 제외(수정 방향의 "security root만"은 fixture엔 맞지 않음 — 이유 주석). app-bootstrap slice/IT 6곳에 security root 제외·import 추가 |
| NEW-12 | 완료 | 이동 대신 ArchUnit 규칙 `BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS`(`CompositionRootBoundaryArchitectureTest.java:75`): `bootstrap.autoconfigure..`에서 `@Component` 메타 annotated 클래스는 `@AutoConfiguration`이어야 함(현재 5 root로 비어있지 않음). `ArchRuleDiscoveryContractTest` 목록 추가. P18이 outbox·idempotency root를 옮기는 중이라 패키지 이동은 피함 |
| P14-new-3 | 완료(수동 명령 경로 선택) | worker를 두지 않고 `ReconcilePosterImageUploadUseCase`가 명시적 명령임을 javadoc에 명시(sample에 trigger 없음, 만들면 PENDING·ABORT_AUTHORIZED 둘 다 골라야 함, `claimPending`은 PENDING만이라 그 선택자가 아님 — 포트 javadoc). `PosterImageAbortReconcileRaceTest.theReconcileCommandFinishesAPendingOrAbortAuthorizedIntent`(두 상태 → READY + attach) PASS. 근거: worker는 새 claim 포트·JPA 쿼리·settings·job·env 키·vendor 테스트가 필요하고, `claimPending`이 handoff claimant를 바꿔 reconcile의 claimant(`poster-image-<opId>`)와 충돌할 수 있어 설계 결정이 더 필요하다. 명령 경로 고정이 더 작다 |
집계: 완료 16, 해당 없음(코드 삭제) 8, 보류 0, 남음 1 (총 25행).
## 제거된 코드
| 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 |
|---|---|---|---|
| `RedisHealthSnapshotProvider` | `src/shared-contract/src/main/java/dev/caskeleton/shared/health/RedisHealthSnapshotProvider.java` | `4fb7943b` | 구현·소비자 0 (A-5b) |
| `opstore` 패키지(`OperationalRecordStorePort`·`OperationalRecord`·`OperationalRecordConflictException`) | `src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/` | `4fb7943b` | 사용처 0 (X1-#6f, S1-#15b, NEW-9b) |
| `DomainContextStrategy`·`DomainContextPropagatorFactory` + 테스트 | `src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/` | `4fb7943b` | case 하나뿐인 확장 지점 (A-10c) |
| `DomainContextSettings`(`ca-skeleton.domain-context.strategy`) | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextSettings.java` | `4fb7943b` | 선택할 전략이 하나 (A-10c) |
| `RateLimitInterceptor.disabled` + 테스트 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptor.java` | `4fb7943b` | M2 이후 dead (I-8d) |
| `GraphQlRequestEnvelopeValidator`·`GraphQlHttpRequestEnvelope` + `GraphQlRequestEnvelopeValidatorTest` | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/` | `4fb7943b` | 요청 경로에서 도달 불가 (J-10d) |
| sample legacy poster image 모드(`LegacyPosterImageController`, `UploadPosterImageUseCase`, `UploadPosterImageCommand`, `LegacyPosterImageAttachment`, `PosterImageApiConfig`, `PosterImageApiSettings`, `LegacyPosterImageUploadCharacterizationTest`) | `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/` | `4fb7943b` | legacy byte[] 업로드 모드와 dual-read (S6-#10b) |
| `MigrationFailedException`·`ProfileMismatchException`·`RequiredAdapterDisabledException`·`StartupValidationException` | `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/` | `f2857840^`(= `b7187e1b`) | 역할 없는 subclass (S6-#13) |
| `ExternalRequestUrlResolver`의 forwarded 파싱 + env `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | `src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java` | `d54909c4` | 컨테이너(RemoteIpValve)와 다른 두 번째 신뢰 판단 (I-5b) |
## 새로 발견한 결함
- `P25-new-1` (미수정, 불안정 테스트): `:adapter:inbound:websocket:systemTest`의 `TomcatWebSocketAbuseIT.shutting down closes live connections rather than dropping them`이 부하 중 한 번 실패(`Expecting actual: 20.000666939S to be less than: 20S` — close를 20초 안에 못 받음). 같은 Gradle 실행에 graphql systemTest가 병렬로 돌고 다른 에이전트 빌드가 겹친 때였고, 단독 `--rerun` 4번은 모두 통과. 변경한 STOMP broker executor는 이 servlet handler 경로(`PlatformWebSocketHandler`)와 무관하다고 판단하지만, 20초 경계에 걸린 타이밍 의존 테스트로 보인다.
- `P25-new-2` (미수정, P18 겹침으로 남김): legacy 업로드 모드 삭제 뒤 `PosterEventPublisher.publishImageAttached`와 domain `PosterImageAttached`(event `poster.image-attached`)의 호출자가 0이다. `PosterEventPublisher`는 P18이 canonical outbox로 바꾸는 파일이라 이 묶음에서는 건드리지 않았다 — 통합 때 함께 삭제하면 된다.
- `P25-new-3` (미수정): sample `application.yml`의 `local` 프로필 문서가 `app.object-storage.enabled: false` 한 줄만 남았다(기본값과 같음). object storage legacy seam(`app.object-storage.legacy.*`) 자체의 정리는 P24 범위라 sample에서는 legacy 활성화만 뺐다.
## 검증
- leaf `check`(compile·test·Spotless·Checkstyle·Error Prone): `:shared-contract` `:application-core` `:application-notification` `:adapter:outbound:support` `:adapter:outbound:cache-redis` `:adapter:inbound:web` `:adapter:inbound:web-notification` `:adapter:inbound:websocket` `:composition:notification-platform` `:adapter:outbound:persistence-jpa` `:adapter:inbound:graphql` `:app-bootstrap` `:sample-portfolio` — 모두 통과.
- 실제 벤더/시스템 lane: `:sample-portfolio:integrationTest` 51/51, `:sample-portfolio:systemTest` 3/3, `:sample-portfolio:webSystemTest` 5/5, `:app-bootstrap:integrationTest` 9/9(Fileserver·ObjectStorage·DurableOperation composition + PostgreSQL idempotency), `:app-bootstrap:systemTest` 8/8, `:app-bootstrap:architectureTest` 통과, `:adapter:outbound:persistence-jpa:jpaPlatformContractTest` 217/217, `:adapter:inbound:graphql:systemTest` 통과, `:adapter:inbound:websocket:systemTest` 18/18(첫 실행 1건 타이밍 실패 → 재실행 4회 통과, P25-new-1), `conditionalTransportQualification` 통과.
- `architectureCheck`, `verifyPublicPathSnapshot`, `:app-bootstrap:verifyEnvKeys`, `verifyDependencyLocks`, `:adapter:inbound:graphql:verifyGraphQlApiSurface` 통과.
- 재생성: `:shared-contract:resolveAndLockAll --write-locks`(testFixtures 설정 추가), `:adapter:inbound:graphql:updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange`(163→161).
- env: 삭제 `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES`, 추가 `APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`(기본 `ko-KR`). 설정 삭제 `ca-skeleton.domain-context.strategy`(env 키 없던 설정). migration 추가 없음.
## 통합 시 겹침 예상
- P18: `app-bootstrap/src/test/.../autoconfigure/{outbox/OutboxSettingsTest,idempotency/IdempotencySettingsTest}.java`(S6-#13 단언 변경), `ConfigurationNamespaceContractTest`(prefix 목록), `SubmitDurableOperationUseCase`(A-4b 시그니처), sample `SamplePortfolioApplication`·yml.
- P24: sample `application.yml` object-storage 블록, `PosterImageObjectStorageConfig`.
@@ -67,6 +67,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| 29 | messaging 카드 검증기 이동에 필요한 YAML 라이브러리 | messaging leaf **테스트에서만** snakeyaml 허용(main 금지 유지), 검증기를 leaf 테스트로 | X1-#7a, X1-지도-readiness |
| 30 | PR `ci`를 변경 모듈만 실행 | 하지 않음 — 전체 실행 + Gradle 캐시 → 보류 | BUILD-계획-B3 |
| 31 | 릴리스 이미지 서명 | 넣음 — cosign keyless, 공식 릴리스 체크섬 고정 설치, tag 릴리스에서 서명·검증 | BUILD-계획-C |
| 32 | fileserver 연산을 use case로 바꿀 때 `@RequiresPermission` | 권한 추가(`file:*`) — 역할 검사(권한)와 소유자·tenant 검사(`FileAccessPolicyPort`)를 둘 다 둔다 | S1-#6b, S1-#18b |
기존 원칙에서 바로 따라 나와 에이전트가 정한 것(소유자가 뒤집을 수 있음):
@@ -114,14 +115,14 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| A-1b | Required | PII 누출 테스트가 메시지 `"connection refused"`로 `@gmail.com` 부재만 확인 → 아무것도 증명 못 함 | 완료 | Wave 1–2 P7 (fcddab7e·Wave 2 커밋): 같은 테스트(`FailOpenDependencyLoggerTest.java:64-79`)가 예외 메시지에 `alice@example.com`·`https://hooks.slack.com/services/...`를 넣고 렌더된 로그에 둘 다 없음을 단언한다. 수정 전 FAIL 확인. 커밋 `9a05d686` | - | 같은 테스트에서 예외 메시지에 `alice@example.com`, `https://hooks.slack.com/services/...`를 넣고 렌더된 로그에 둘 다 없음을 단언 |
| A-2a | Required | websocket이 prod 판정을 손으로 재구현(`"prod".equals`, trim/소문자 없음) → `Prod` 프로필에서 prod 안전 검증 건너뜀 | 해당 없음(코드 삭제) | 「제거된 코드」 표 `app.websocket.platform.*` 설정(`WebSocketPlatformSafetyConfiguration`, `WebSocketPlatformStartupValidator` 포함) 행. `git log --diff-filter=D`로 `6d27356e` 삭제 확인, 현재 websocket main에 `getActiveProfiles` 호출 0건 | - | - |
| A-2b | Required | `RuntimeProfileSnapshot` Javadoc "repository에서 `getActiveProfiles`를 읽는 유일한 production 타입" 주장이 거짓 | 남음 | `src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/runtime/RuntimeProfileSnapshot.java:12-13`. 직접 읽는 곳: `src/adapter/inbound/graphql/.../autoconfigure/GraphQlPlatformAutoConfiguration.java:123`, `src/adapter/outbound/fileserver/.../platform/autoconfigure/FileserverSecurityConfiguration.java:81`, `src/adapter/outbound/httpclient/.../autoconfigure/HttpClientProfileAutoConfiguration.java:155-156`, `src/adapter/outbound/objectstorage/.../config/ObjectStorageCapabilityConfig.java:59-61` | W5 | `RuntimeProfileSnapshot.java:12-13` 문장을 "composition root(app-bootstrap)의 reader"로 좁히거나 삭제 |
| A-2c | Required | BOOT-002 가드 ArchUnit이 `dev.caskeleton.bootstrap..`만 검사 → 다른 leaf의 새 profile reader·손 판정은 못 잡음 | 남음 | `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java:12-21` (변경 없음, `git diff 208077fd 6d27356e` 0줄) | W3 | 같은 규칙을 `dev.caskeleton..`(messaging·sample 제외)로 넓히고 `getActiveProfiles` 호출 허용 목록을 현재 5곳(`RuntimeProfileSnapshot`, 위 graphql·fileserver·httpclient·objectstorage 클래스)으로 고정 — support에 의존 못 하는 graphql·objectstorage가 있어 snapshot 강제는 불가 |
| A-2c | Required | BOOT-002 가드 ArchUnit이 `dev.caskeleton.bootstrap..`만 검사 → 다른 leaf의 새 profile reader·손 판정은 못 잡음 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `RuntimeProfileAccessArchitectureTest`를 `@AnalyzeClasses(packages = "dev.caskeleton")`, `resideOutsideOfPackages(messaging.., sample..)`로 넓히고 허용 목록 `PROFILE_READERS`(`app-bootstrap/src/architectureTest/.../RuntimeProfileAccessArchitectureTest.java:29`)를 5곳(RuntimeProfileSnapshot, GraphQlPlatformAutoConfiguration, FileserverSecurityConfiguration, HttpClientProfileAutoConfiguration, ObjectStorageCapabilityConfig)으로 고정. 규칙이 실제로 무는지: 목록에서 graphql·objectstorage를 빼고 돌려 FAIL(`Rule 'BOOT-002: …' was violated (3 times): … GraphQlPlatformAutoConfiguration.graphQlPlatformConfigurationCheck … calls method <Environment.getActiveProfiles()>`) 확인 후 원복 → PASS | - | 같은 규칙을 `dev.caskeleton..`(messaging·sample 제외)로 넓히고 `getActiveProfiles` 호출 허용 목록을 현재 5곳(`RuntimeProfileSnapshot`, 위 graphql·fileserver·httpclient·objectstorage 클래스)으로 고정 — support에 의존 못 하는 graphql·objectstorage가 있어 snapshot 강제는 불가 |
| A-2d | Required | `RuntimeEnvironment` Javadoc이 bridge를 "app-bootstrap's `RuntimeProfileSnapshot`"이라 하고 bootstrap 외 reader가 없다고 서술 | 남음 | `src/shared-contract/src/main/java/dev/caskeleton/shared/runtime/RuntimeEnvironment.java:29-36` (bridge는 `adapter:outbound:support`에 있음) | W5 | `RuntimeEnvironment.java:32-36`을 "support의 `RuntimeProfileSnapshot` 또는 `getActiveProfiles` 결과를 직접 넘기는 platform config"로 정정 |
| A-3 / X1-#1e | Required | outbox V2 단건 발행 코드(`PublishNextOutboxDeliveryUseCase`, `OutboxV2RetryPolicy`)가 테스트 0·호출자 0, 동기 publish에 timeout 미적용 | 해당 없음(코드 삭제) | 「제거된 코드」 표 "application-core outbox V2 포트·유스케이스 17종" 행(D2). `git grep PublishNextOutboxDelivery\|OutboxV2RetryPolicy -- src` 0건. 남은 v1 relay는 lease 만료 시 `STALE`로 기록(`src/application-core/src/main/java/dev/caskeleton/application/outbox/PublishPendingOutboxEventsUseCase.java:25-26`)<br>X1-#1e: `OutboxV2RetryPolicy`·`PublishNextOutboxDeliveryUseCase` 삭제(`docs/capability-status.md:175`), main 참조 0 | - | - |
| A-4a | Required | operation 조회·취소 유스케이스가 없어 web이 store 포트·트랜잭션·owner/tenant 인가를 직접 수행 (= I-1, Critical #12) | 완료 | `src/application-core/src/main/java/dev/caskeleton/application/operation/GetDurableOperationUseCase.java:14-51`(QueryUseCase + `@UseCaseCapability`), `CancelDurableOperationUseCase.java:74-121`(CommandUseCase + `@RequiresPermission` + `@UseCaseCapability`), 인가 `DurableOperationAccessPolicy.java:147-150`. web `OperationQueryService`는 「제거된 코드」 "durable operation HTTP 투영" 행. 테스트 `GetDurableOperationUseCaseTest.submitterInAnotherTenantReadsNothing`, `CancelDurableOperationUseCaseTest.submitterInAnotherTenantIsAnsweredAsIfTheOperationDidNotExist`, `DurableOperationAccessPolicyTest.onlyTheSubmitterInTheSubmittingTenantMayAccess`. 커밋 `6d27356e` | - | - |
| A-4b | Required | `SubmitDurableOperationUseCase`가 `CommandUseCase`를 구현하지 않음(자체 `submit` 메서드), production 호출자 0 | 남음 | `src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java:53,85`. `LegacyOutboxAppendPort` 사용(`:56`)은 MSG-015 문서화된 seam(`src/messaging/CLAUDE.md:75-78`) | W3 | `SubmitDurableOperationUseCase`가 `CommandUseCase<OperationCommand, OperationAcceptance>`를 구현하고 `submit`→`handle`로 이름 변경(Get/Cancel과 같은 모양) |
| A-4b | Required | `SubmitDurableOperationUseCase`가 `CommandUseCase`를 구현하지 않음(자체 `submit` 메서드), production 호출자 0 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `SubmitDurableOperationUseCase implements CommandUseCase<OperationCommand, OperationAcceptance>`, `submit`→`handle`(`application-core/.../operation/SubmitDurableOperationUseCase.java:54,88`), `OperationCommand implements Command`. `SubmitDurableOperationUseCaseTest`의 필드 타입을 `CommandUseCase<…>`로 바꿔 FAIL(`type argument OperationCommand is not within bounds of type-variable C` / `SubmitDurableOperationUseCase cannot be converted to CommandUseCase`)→PASS. 호출부(`DurableOperationController`, postgresql IT) 갱신, `jpaPlatformContractTest` 217/217 | - | `SubmitDurableOperationUseCase`가 `CommandUseCase<OperationCommand, OperationAcceptance>`를 구현하고 `submit`→`handle`로 이름 변경(Get/Cancel과 같은 모양) |
| A-5a | Required | shared-contract README가 "1001번째 tenant부터 bucket folding 자동 적용"을 약속하지만 적용 코드 없음 | 남음 | `src/shared-contract/README.md:350`. `CardinalityBounds`·`MetricNaming` main 참조 0(테스트 `MetricsAlertingContractTest`만), 실제 필터 `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/metrics/MetricsCardinalityMeterFilter.java`는 `ForbiddenMetricTags`만 사용 | W5 | `src/shared-contract/README.md:350`의 자동 folding 문장 삭제(연결은 필요해질 때) |
| A-5b | Required | `RedisHealthSnapshotProvider` 구현·소비자 0인데 CLAUDE.md는 "adapters and bootstrap health composition이 사용"이라 서술 | 남음 | `src/shared-contract/src/main/java/dev/caskeleton/shared/health/RedisHealthSnapshotProvider.java`(참조는 자기 파일·문서뿐), `src/shared-contract/CLAUDE.md:22-23`, `src/shared-contract/README.md:15` | W3 | `RedisHealthSnapshotProvider.java` 삭제 + `shared-contract/CLAUDE.md:22-23`, `README.md:15` 문장 삭제 |
| A-5c | Required | 소비자 없는 "계약" 타입(`AlertSeverity`, `BaggageAllowlist`, `CardinalityBounds`, `MetricNaming`)이 main에 있음 — 테스트에서만 사용 | 남음 | `src/shared-contract/src/main/java/dev/caskeleton/shared/metrics/{AlertSeverity,CardinalityBounds,MetricNaming}.java`, `.../shared/tracing/BaggageAllowlist.java`. main 참조 0, 사용처는 `src/app-bootstrap/src/test/.../contract/MetricsAlertingContractTest.java`, `DistributedTracingContractTest.java` | W3 | 4개 타입을 shared-contract `testFixtures`로 옮기거나 삭제하고 README(`:367,375,403`) 절 정리 |
| A-5b | Required | `RedisHealthSnapshotProvider` 구현·소비자 0인데 CLAUDE.md는 "adapters and bootstrap health composition이 사용"이라 서술 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `shared/health/RedisHealthSnapshotProvider.java` 삭제, `shared-contract/CLAUDE.md`·`README.md` 문장 삭제 | - | `RedisHealthSnapshotProvider.java` 삭제 + `shared-contract/CLAUDE.md:22-23`, `README.md:15` 문장 삭제 |
| A-5c | Required | 소비자 없는 "계약" 타입(`AlertSeverity`, `BaggageAllowlist`, `CardinalityBounds`, `MetricNaming`)이 main에 있음 — 테스트에서만 사용 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `MetricNaming`·`CardinalityBounds`·`AlertSeverity`·`BaggageAllowlist`를 shared-contract `src/testFixtures`로 이동(`java-test-fixtures` + `gradle.lockfile` 재생성), app-bootstrap `testImplementation(testFixtures(project(':shared-contract')))`. main에는 `ForbiddenMetricTags`만 남음. README metrics 절·CLAUDE.md 책임 목록 정리. 기존 계약 테스트 그대로 PASS | - | 4개 타입을 shared-contract `testFixtures`로 옮기거나 삭제하고 README(`:367,375,403`) 절 정리 |
| A-6a | Required | application-core CLAUDE.md/README가 코드와 다름: application-notification 소유 타입을 core 절로 설명, operation·cache·lease·realtime 절 없음 | 남음 | `src/application-core/CLAUDE.md:76-80`(Notification 절), `src/application-core/README.md:495-530`(`NotificationPort`를 "application-core로 옮긴" 타입으로 서술 — 실제 `src/application-notification/src/main/java/dev/caskeleton/application/notification/NotificationPort.java`). 헤더 목록에 operation/cache/lease/realtime 없음(패키지는 `src/application-core/src/main/java/dev/caskeleton/application/{operation,cache,lease,realtime}/` 존재) | W5 | application-core `CLAUDE.md:76-80`·`README.md:495-530` 알림 절을 application-notification 문서로 옮기고, README에 operation(Get/Cancel/Submit)·cache(`CacheRegionPort`)·lease·realtime(`LiveEventReplayPort`) 절 추가 |
| A-6b | Required | identifier CLAUDE.md가 없는 ArchUnit 규칙과 없는 hook을 인용 | 남음 | `src/adapter/outbound/identifier/CLAUDE.md:33`(`identifier_adapter_does_not_depend_on_other_adapters_or_bootstrap` — `git grep` 결과 이 파일뿐), `:34`(`.claude/hooks/ca_import_gate.py` 없음), `:8` Boot 4.0.0. 의존성(`:28`)·테스트 이름(`:41`)은 `6d27356e`에서 고쳐짐 | W5 | `identifier/CLAUDE.md:32-34`를 "modules.json 방향 게이트가 차단"으로 교체, `:8` 버전 삭제 |
| A-6c | Required | identifier README 패키지 루트·SSOT 오기, 삭제된 UUID 능력을 설명 | 남음 | `src/adapter/outbound/identifier/README.md:3`(`dev.caskeleton.adapter.identifier`, 실제 `...adapter.outbound.identifier`), `:50`(`src/build.gradle`의 `allowedProjectDependencies`), `:11-12` UUIDv7 식별자 생성(main엔 `HmacUserPrincipalPseudonymizer`만). Spock 절은 삭제됨 | W5 | `identifier/README.md:3`, `:50`을 실제 패키지·`src/config/architecture/modules.json`으로, `:11-12` UUID 문장 삭제 |
@@ -136,7 +137,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| A-9c | Consider | `@Deprecated(forRemoval)` `FileExportPort` 호출자 0 | 해당 없음(코드 삭제) | 「제거된 코드」 표 "`FilePublicationPort`·`FileExportPort` 계약" 행 | - | - |
| A-10a | Nit | identifier가 `ca.spring-library`를 써서 순수 단위 테스트에 webmvc-test·tomcat 유입 | 남음 | `src/adapter/outbound/identifier/build.gradle:2` (main은 Spring 어노테이션 없는 `HmacUserPrincipalPseudonymizer` 하나) | W5 | `identifier/build.gradle:2`를 `id 'ca.java-library'`로(lockfile 갱신) |
| A-10b | Nit | `MasterSwitch.java:57-66` 주석 줄 깨짐 | 해당 없음(코드 삭제) | 「제거된 코드」 표 "`MasterSwitch`, `MasterSwitchParser`, `MasterSwitchParseResult`" 행 | - | - |
| A-10c | Nit | `DomainContextStrategy`/`DomainContextPropagatorFactory`가 case 하나뿐인 확장 지점 | 남음 | `src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextStrategy.java:12-19`(`THREAD_LOCAL` 하나), `DomainContextPropagatorFactory.java:14-18`, 바인딩 `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextSettings.java:12-16` | W3 | enum·factory·`DomainContextSettings`(`ca-skeleton.domain-context.strategy`)를 지우고 호출부가 `new ThreadLocalDomainContextPropagator()`를 직접 쓴다 |
| A-10c | Nit | `DomainContextStrategy`/`DomainContextPropagatorFactory`가 case 하나뿐인 확장 지점 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `DomainContextStrategy`·`DomainContextPropagatorFactory`·`DomainContextSettings`(`ca-skeleton.domain-context`)·`DomainContextPropagatorFactoryTest` 삭제, `DomainContextConfig`가 `new ThreadLocalDomainContextPropagator()`. `ConfigurationNamespaceContractTest`의 prefix 목록에서 제거하고 스캔 비어있음 가드를 `hasSizeGreaterThan(10)`→`isNotEmpty()`(prefix 하나 줄어 10개가 됨) | - | enum·factory·`DomainContextSettings`(`ca-skeleton.domain-context.strategy`)를 지우고 호출부가 `new ThreadLocalDomainContextPropagator()`를 직접 쓴다 |
| L-1 | Critical | outbox relay `@Scheduled`가 `@EnableScheduling` 없이는 안 돌고, 유일한 `@EnableScheduling`이 idempotency=jdbc 조건부 (Critical #5) | 완료 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfig.java:54` `@EnableScheduling`(outbox 켜짐 + `OutboxStorePort` bean 조건). 테스트 `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxConfigTest.java:28` `outboxCapabilityEnablesSchedulingWithIdempotencyDisabled`. `OutboxReaper`(persistence-jpa)도 같은 `ca-skeleton.outbox.enabled` 조건이라 함께 동작. 커밋 `6d27356e` | - | - |
| L-2a | Required | prod가 에러 상세(stacktrace/message/exception) 노출을 막는다고 적었지만 검사 코드가 없음 | 완료 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidator.java:39-62`(include-stacktrace/message/binding-errors ≠ never, include-exception=true → exit 71), 등록 `RuntimeSafetyConfig.java:28-31`. 테스트 `ErrorDetailExposureSafetyValidatorTest.prodRefusesToStartWhenErrorDetailsWouldReachClients`, `prodStartsWhenEveryErrorDetailStaysHidden`. 문서 `application-prod.yml:13`, `src/README.md:216-218`, `src/app-bootstrap/README.md:177-178,680-681` 정정. 커밋 `6d27356e` | - | - |
| L-2b | Required | `config/runtime.yml` 주석이 multi-instance를 "prod profile이 기동 시 강제", "instance-coordination bean 5종 필요"라고 서술(실제 검사는 profile 무관·lock provider 1개) | 남음 | `src/app-bootstrap/src/main/resources/config/runtime.yml:11-13` vs `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidator.java:42-61` | W5 | `runtime.yml:11-13`을 "true면 `distributedLockProvider`(persistence-jpa)가 없을 때 기동 실패(exit 72)"로 교체 |
@@ -430,14 +431,14 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| I-4a | Required | `RequestLoggingFilter`가 Spring Security 뒤에서 돌아 401/403 응답 meta id가 null, 접근 로그 누락 | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): request/correlation/trace/span id 발급·MDC·응답 헤더를 `WebMvcRequestIdFilter`(HIGHEST+10, Security 앞) 한 곳으로 이동(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/filter/WebMvcRequestIdFilter.java:95,103`), ERROR/ASYNC 재디스패치에 같은 값 복원. `SecurityModeWebContractTest.anUnauthenticatedRejectionCarriesTheAssignedRequestIdInItsMeta`(실제 JWT security 체인이 쓴 401 Envelope의 `meta.requestId` = `X-Request-Id`) FAIL(`expected: "13499754-…" but was: null`)→PASS. `WebMvcRequestIdFilterTest.assignedIdentifiersAreOnMdcDuringTheChainAndMatchWhatTheResponseCarries`·`inboundCorrelationIdLosesLineBreaksBeforeReachingMdc` FAIL(`No value present` / `expected "fooFAKE LOG" but was null`)→PASS, `mdcIsClearedWhenTheRequestLeavesTheFilter`·`anErrorRedispatchRestoresTheSameIdentifiersOnMdc` PASS. 순서: `OperationalContractRuntimeTest.requestIdFilterIsRegisteredAheadOfSpringSecurity`(`src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java:135`, 슬라이스에 `SecurityFilterAutoConfiguration`을 넣어 실제 `springSecurityFilterChain` 등록과 비교) PASS. fixture 문제: `PipelineOrderFixtureApplication`은 의미 순서·async 1회 관측만 증명한다고 주석에 적고 실제 순서는 위 두 테스트가 맡음. `RequestLoggingFilter`는 principal을 읽으려고 보안 체인 안쪽에 남음 → 체인이 거절한 요청의 접근 로그 줄은 없고 entry point/access-denied handler의 `security failure` 로그(이제 request_id 포함)가 대신함 | - | MDC(request/correlation/trace id) 채우기를 `WebMvcRequestIdFilter`(HIGHEST+10)로 옮기고 `OperationalContractRuntimeTest`에 "request-id 필터 order < `springSecurityFilterChain` order" 단언 추가 |
| I-4b | Required | trace id를 두 필터가 따로 생성해 서로 불일치 | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): trace는 `WebMvcRequestIdFilter`만 만든다(`TraceParent.parse` 또는 새 root, WebTraceId·MDC·응답 `traceparent`가 같은 값). `RequestLoggingFilterTest.assignsNoIdentifierOrTraceOfItsOwn` FAIL(`Expecting [X-Request-Id, X-Correlation-Id, traceparent] not to contain …`)→PASS, `WebMvcRequestIdFilterTest.responseTraceparentCarriesTheTraceIdTheFilterAssigned`·`validInboundTraceparentIsAdoptedWithItsSpanAndEchoed` FAIL(`NullPointerException` — 헤더 없음)→PASS. `RequestLoggingFilter`의 id/trace 생성 코드 삭제(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/filter/RequestLoggingFilter.java`), 옮겨진 테스트는 `WebMvcRequestIdFilterTest`로 | - | `RequestLoggingFilter`는 `WebMvcRequestIdFilter.traceId(request)`만 읽고 생성하지 않음 |
| I-5a | Required | `FORWARDED_HEADERS_TRUSTED` 레이트리밋 키가 XFF 맨 왼쪽 값을 peer 검증 없이 사용 → 비인증 레이트리밋 우회 | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): 커밋 `983cc832`(W1). 결정대로 `FORWARDED_HEADERS_TRUSTED` 모드 삭제. 비인증 키는 `getRemoteAddr()` 하나(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitKeyResolver.java:45`). `RateLimitWebConfigTest.spoofedForwardedForDoesNotChangeTheUnauthenticatedKey`(Review Focus 3: 옛 `client-ip-mode=forwarded-headers-trusted`를 남긴 배포에서 위조 XFF 두 개를 보내도 키가 peer 주소 하나) FAIL(`Expecting actual ["9:CLIENT_IP\|12:198.51.100.1\|…", "…198.51.100.2…"] to contain exactly ["9:CLIENT_IP\|11:203.0.113.7\|…" ×2]`)→PASS. `server.forward-headers-strategy=framework`면 rate limit 켤 때 기동 거부(`RateLimitWebConfig.java:38`), `RateLimitWebConfigTest.frameworkForwardHeadersStrategyIsRefusedWhileRateLimiting` FAIL(`context started successfully`)→PASS. env 키 `APP_RATE_LIMIT_CLIENT_IP_MODE`·설정 키 `app.rate-limit.client-ip-mode` 삭제(`env-keys.yaml`, `.env.example`, `cache-redis.yml`, sample `application.yml`, README 2곳). `APP_SERVER_FORWARD_HEADERS_STRATEGY` allowed_values `[none, native]`, `.env.example` 값 `framework`→`native`, `server.yml` 주석에 `native` + `server.tomcat.remoteip.internal-proxies` 명시 | - | 이 모드를 삭제하고 `server.forward-headers-strategy=native` + `server.tomcat.remoteip.internal-proxies`로 `getRemoteAddr()`를 쓰는 `REMOTE_ADDR_ONLY` 하나로(운영 정본은 `forward-headers-strategy`라는 W3-2b 결정과 일치) |
| I-5b | Required | forwarded 헤더 신뢰 판단이 여러 곳에 흩어짐 | 남음 | `TrustedProxyPolicy`·reactive 콜백은 삭제됐으나 3곳 남음: `src/app-bootstrap/src/main/resources/config/server.yml:11`(`forward-headers-strategy`), `src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java:31-53`(정확 문자열 집합), I-5a resolver(검증 없음) | W3 | `ExternalRequestUrlResolver`의 forwarded 파싱과 I-5a 모드를 지우고 Tomcat RemoteIpValve(`forward-headers-strategy=native`)가 고친 `getScheme/getServerName/getRemoteAddr`만 사용 |
| I-5b | Required | forwarded 헤더 신뢰 판단이 여러 곳에 흩어짐 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `ExternalRequestUrlResolver`의 `Forwarded`/`X-Forwarded-*` 파싱과 trusted-proxy 목록 삭제, 컨테이너 값만 사용(`web-notification/.../callback/ExternalRequestUrlResolver.java:20`). env `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES`·설정 `…callbacks.trusted-proxies` 삭제(`env-keys.yaml`, `.env.example`, `notification.yml`, composition README). `ExternalRequestUrlResolverTest.forwardedHeadersOnTheRequestDoNotChangeTheResolvedUrl` FAIL(`expected: "http://internal.local:8080/callbacks/ses?a=1" but was: "https://attacker.example/callbacks/ses?a=1"`, trusted peer 설정 시)→PASS. `NotificationCallbackMvcControllerTest` 두 케이스 갱신 | - | `ExternalRequestUrlResolver`의 forwarded 파싱과 I-5a 모드를 지우고 Tomcat RemoteIpValve(`forward-headers-strategy=native`)가 고친 `getScheme/getServerName/getRemoteAddr`만 사용 |
| I-6a | Required | category 생략 시 컨트롤러가 `"transactional"`을 넣어 marketing suppression이 적용되지 않음(HARD-STOP 4 후보) | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): 결정 13. 컨트롤러의 `DEFAULT_CATEGORY="transactional"` 삭제, `request.category()`를 그대로 넘김(`NotificationSubmissionController.java:87`). 판정은 `AcceptNotificationCommand`(application-notification, `AcceptNotificationCommand.java:70`)가 → `IllegalArgumentException` → 400 `BAD_PARAMETER`. `NotificationSubmissionControllerTest.submissionWithoutCategoryIsRejectedBeforeTheUseCaseRuns` FAIL(`[500, 1]` — 유스케이스가 transactional로 호출됨)→PASS(`[400, 0]`), `AcceptNotificationApplicationUseCaseTest.anAcceptanceWithoutCategoryIsRefusedRatherThanDefaulted` PASS(소유자 명시) | - | 결정(2026-09-25): category 필수 — 생략하면 400, 판정은 유스케이스로 이동 |
| I-6b | Required | 템플릿 버전 기본값 `1`, locale 기본값 `Locale.getDefault()`(호스트 JVM)를 컨트롤러가 결정 | 남음 | `.../submission/NotificationSubmissionController.java:48-49,82-84,121-123`, `.../submission/NotificationTemplateController.java:75`(경로 prefix는 I-6a와 같음) | W3 | 세 값을 command에서 `Optional`로 받고 기본값은 알림 유스케이스가 설정값으로 적용 |
| I-6b | Required | 템플릿 버전 기본값 `1`, locale 기본값 `Locale.getDefault()`(호스트 JVM)를 컨트롤러가 결정 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `AcceptNotificationCommand.templateVersion`·`locale`, `PublishNotificationTemplateCommand.version`을 `Optional`로. 기본값은 유스케이스가 적용: `NotificationTemplateVersion.FIRST_VERSION`, 새 설정 `ca-skeleton.notification.platform.default-locale`(`APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE`, 기본 `ko-KR`, ROOT 거부) — `AcceptNotificationApplicationUseCase.java:134-135`, `PublishNotificationTemplateApplicationUseCase.java:82`. 컨트롤러의 `Locale.getDefault()`·`DEFAULT_TEMPLATE_VERSION` 제거. 새 테스트 `aCommandNamingNoVersionOrLocaleGetsTheFirstVersionAndTheConfiguredLocale`, `theRootLocaleIsRefusedAsTheConfiguredDefault`, `aPublicationNamingNoVersionPublishesTheFirstVersion`(시그니처 변경이라 FAIL 단계는 컴파일 오류). 기본 locale 값 `ko-KR`은 소유자 결정 11(한국어)에 맞춘 선택 — 다르게 원하면 env 한 줄 | - | 세 값을 command에서 `Optional`로 받고 기본값은 알림 유스케이스가 설정값으로 적용 |
| I-7 | Required | `wire-type-manifest.yaml`이 런타임에 없는 wire 계약(`LONG: INTEGER_STRING`, `BIG_DECIMAL: DECIMAL_STRING`)을 공개 | 남음 | 기본 web의 bean은 삭제(`WebMvcPlatformAutoConfiguration` 3 bean)됐지만 opt-in leaf로 옮겨져 남음: `src/adapter/inbound/web-advanced/src/main/resources/META-INF/web/wire-type-manifest.yaml:3-9,25-30`, `.../web-advanced/src/main/java/dev/caskeleton/adapter/inbound/web/advanced/contract/WebWireTypeManifest.java`. 적용하는 Jackson 설정 없음 | W5 | 소비자 0이므로 yaml과 `advanced/contract/` 4개 타입·테스트를 삭제하고 web-advanced README.md:45 행 정리 |
| I-8a | Consider | 운영 소비자 없는 라이브러리 코드가 기본 web leaf에 있고 운영 경로와 중복 | 완료 | 기본 web leaf 패키지는 `auth·authz·conditional·config·controller·core·envelope·error·filter·http·mvc·observability·pagination·ratelimit·settings`만(`security/cache/openapi/idempotency` 없음). 라이브러리는 opt-in `src/adapter/inbound/web-advanced`(README.md:45 목록), 중복 세대는 삭제(제거 표 「forwarded header 라이브러리」「CORS/CSRF 프로필」「cache 정책 카탈로그」「JSON mapper factory」「OpenAPI customizer」). D1 결정, 커밋 `6d27356e` | - | - |
| I-8b | Consider | 더 엄격한 CORS 규칙(`WebCorsPolicyValidator`)을 `CorsSettings`에 합치지 않고 삭제만 함 → 기동 시 origin 형식 검증 없음 | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): NEW-10b와 같은 수정. `CorsSettingsTest.originThatIsNotExactlySchemeHostPortFailsWithTheEnvKeyName`(10개 입력) FAIL(`Expecting actual not to be null` — 예외 없음)→PASS, `exactOriginWithPortIsAccepted` PASS. `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/settings/CorsSettings.java:44,64`. 옛 validator 규칙 중 둘은 넣지 않음: "소문자만"(Spring `CorsConfiguration.checkOrigin`이 대소문자 무시 비교), "credentials면 allowedHeaders `*` 거부"(Spring은 `*`를 요청 헤더 목록으로 되돌려 주므로 credentials와 함께 동작한다 — 넣으면 지금 동작하는 기본값(`*`)을 깨뜨림) | - | `CorsSettings` compact constructor에 옛 validator 규칙(origin = scheme://host[:port] 소문자·경로 없음·와일드카드 없음, credentials면 헤더 `*` 거부) 추가 + 거부 테스트 |
| I-8c | Consider | `observability/WebAuditPublisher` 참조 0 | 해당 없음(코드 삭제) | 제거 표 「2세대 관측 (`WebAccessLog*`, `WebAudit*` …)」, HEAD grep 0 | - | - |
| I-8d | Consider | `RateLimitInterceptor.disabled(...)`가 M2 이후 dead | 남음 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptor.java:48`, 호출은 `src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptorTest.java:137`뿐 | W3 | `disabled` 팩토리와 그 테스트 삭제 |
| I-8d | Consider | `RateLimitInterceptor.disabled(...)`가 M2 이후 dead | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `RateLimitInterceptor.disabled`와 null-bridge 분기·`disabledModeHasNoProviderOrPseudonymizerSideEffects` 삭제, 팩토리 `enabled`는 public 생성자로 | - | `disabled` 팩토리와 그 테스트 삭제 |
| I-8e | Consider | `cursor/CursorCodec.withDevKey()` 키 하드코딩 | 해당 없음(코드 삭제) | 제거 표 「서명 커서 코덱 (`CursorCodec`, `CursorException`)」, HEAD grep 0 | - | - |
| I-9a | Consider | `problem-catalog.yaml` `VALIDATION_FAILED` 422 vs `OperationalError` 400 | 해당 없음(코드 삭제) | 제거 표 「WebProblem 어휘 (… `problem-catalog.yaml` …)」 | - | - |
| I-9b | Consider | README D5에 opt-in problem 경로(`spring.mvc.problemdetails.enabled`) 미기재 | 해당 없음(코드 삭제) | opt-in problem 경로 삭제(제거 표 「WebProblem 어휘」). 현재 README는 거부만 기재 `src/adapter/inbound/web/README.md:174`, `src/app-bootstrap/src/main/resources/application.yml:17-22` false 고정 | - | - |
@@ -452,14 +453,14 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| J-4c | Required | DataLoader 실패 테스트가 `getErrors().isNotEmpty()`만 단언 | 남음 | `src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlBatchLoaderRegistrationTest.java:137,150,166,202` | W4 | 각 실패의 wire `extensions.code`/`category`를 단언 |
| J-5 / X1-#2d | Required | stable extensions allowlist가 아무도 처리하지 않는 `idempotencyKey`를 허용 | 완료 | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlExtensionsPolicy.java:40-42`(`stableDefaults()` → `none()`), 테스트 `GraphQlRequestEnvelopeValidatorTest.stableDefaultsRejectAnIdempotencyKeyExtensionAsUnregistered`. 제거 표 「GraphQL mutation 멱등성」. 커밋 `6d27356e`<br>X1-#2d: `GraphQlExtensionsPolicy.java:29` 기본 allowlist `Set.of()`, mutation 멱등성 타입 삭제(`docs/capability-status.md:231`), 커밋 `6d27356e` | - | - |
| J-6 | Required | `GraphQlClientPolicy.persistedOperationOnly`가 아무 동작도 안 함(fail-open) | 해당 없음(코드 삭제) | 제거 표 「`GraphQlClientPolicy`의 `persistedOperationOnly`·`maxResponseNodes`·`maxResponseBytes`」, graphql src grep 0 | - | - |
| J-7 | Consider | preparsed 캐시가 조회마다 전역 lock 아래 전체 항목을 순회 | 남음 | `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProvider.java:167-177`(끝까지 순회). 맵은 이미 access-order(`:57`) | W3 | `expireIdle`에서 첫 미만료 항목을 만나면 `break`(access-order라 뒤는 모두 더 최근) |
| J-7 | Consider | preparsed 캐시가 조회마다 전역 lock 아래 전체 항목을 순회 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `BoundedPreparsedDocumentProvider.expireIdle`이 첫 미만료 항목에서 `return`(`graphql/.../execution/BoundedPreparsedDocumentProvider.java:180`). 새 `aReaccessedEntryOutlivesAnOlderIdleOneEvenWhenItWasCachedFirst` PASS(성능 변경이라 동작 FAIL 재현 없음 — 순서 보존만 고정) | - | `expireIdle`에서 첫 미만료 항목을 만나면 `break`(access-order라 뒤는 모두 더 최근) |
| J-8 | Consider | 인가 root 타입 이름을 `"Query/Mutation/Subscription"` 리터럴로 고정 → root 이름을 바꾸면 규칙 미적용(allow 규칙 fail-open) | 완료 | Wave 1–2 P8 (fcddab7e·Wave 2 커밋): `runtime/GraphQlDocumentAuthorizationHandlerTest.aProtectedFieldOnARenamedRootTypeIsStillDenied`(query·mutation 2건), `aContextWithoutASchemaIsRefusedInsteadOfGuessingRootNames` FAIL(`Expecting actual not to be null` — 거부 없이 통과) → PASS. root 이름을 `context.schema().getQueryType()/getMutationType()/getSubscriptionType()`에서 읽고, schema나 해당 root가 없으면 `IllegalStateException`(→ INTERNAL_ERROR, fail-closed). `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlDocumentAuthorizationHandler.java:68,87`. 커밋 `0392d8c9` | - | `context.schema().getQueryType()/getMutationType()/getSubscriptionType()`의 이름 사용 |
| J-9a | Consider | body-cap 필터 스트리밍 경로에서 `BodyTooLargeException`이 감싸이면 413 대신 500 가능 | 완료 | Wave 1–2 P8 (fcddab7e·Wave 2 커밋): 재현됨. systemTest `runtime/GraphQlPlatformExecutionPathTest.aChunkedBodyOverTheRawCapIsRefusedWith413`(Content-Length 없는 chunked 200KB 본문) FAIL(`expected: 413 but was: 500`) → PASS. 원인: `FrameworkServlet`(spring-webmvc 7.0.9 `FrameworkServlet.java:1006-1008`)이 decoder 안에서 던진 unchecked `BodyTooLargeException`을 `ServletException("Request processing failed")`으로 감쌈. `IOException/ServletException/RuntimeException`을 잡아 cause chain(최대 16단계)에서 찾으면 413, 아니면 그대로 rethrow. `.../runtime/servlet/GraphQlRequestBodyLimitFilter.java:85,98`. 커밋 `aa5f4d90` | - | catch를 `Exception`으로 넓혀 cause chain에서 `BodyTooLargeException`을 찾으면 413 |
| J-9b | Consider | body-cap 필터의 chunked(Content-Length 없음) 경로 테스트 없음 | 남음 | graphql test·systemTest에 `chunked`/`Transfer-Encoding`/`BodyTooLarge` grep 0 | W4 | systemTest에 Content-Length 없는 chunked 초과 본문 → 413 케이스 추가 |
| J-10a | Consider | `advanced/**` 134파일 도달 불가 | 해당 없음(코드 삭제) | 제거 표 「graphql `advanced/**` 전체」 | - | - |
| J-10b | Consider | `compat`·`release`·`moduleboundary`(테스트 데이터가 운영 jar에) 도달 불가 | 해당 없음(코드 삭제) | 제거 표 「graphql 스키마 호환성 비교기 `compat/`」「graphql 릴리스 게이트 `release/`」「graphql 모듈 경계 모델 `moduleboundary/`」 | - | - |
| J-10c | Consider | `fetch`·`mutation`(·`pagination`) 패키지가 요청 경로에서 도달 불가 | 완료 | D1(분류 2) 결정대로 라이브러리 API로 등재: `src/adapter/inbound/graphql/README.md:214-226`, `CLAUDE.md:162`. graphql은 opt-in capability라 기본 조립에 실리지 않음. 커밋 `6d27356e` | - | - |
| J-10d | Consider | `http/` 병렬 HTTP 계층이 도달 불가 | 남음 | 9개는 삭제(제거 표 「병렬 HTTP 전송 모델」), 남은 `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidator.java`·`GraphQlHttpRequestEnvelope.java`는 테스트(`GraphQlRequestEnvelopeValidatorTest`, `GraphQlRequestBoundsTest`)만 참조, README 라이브러리 목록에도 없음 | W3 | 두 타입을 삭제하고 테스트는 실제 경로(`GraphQlPlatformWebInterceptor.verifyRequestBounds`, `GraphQlRequestSize`, `GraphQlJsonStructurePolicy`) 대상으로 옮김 |
| J-10d | Consider | `http/` 병렬 HTTP 계층이 도달 불가 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `GraphQlRequestEnvelopeValidator`·`GraphQlHttpRequestEnvelope`·`GraphQlRequestEnvelopeValidatorTest` 삭제. 한도 테스트는 실제 경로로: `runtime/GraphQlPlatformWebInterceptorRequestBoundsTest`(auto-configured interceptor로 document/variables byte·depth·미등록 extension 거부 5건), `GraphQlRequestBoundsTest`는 `GraphQlJsonValues`·`GraphQlRequestSize`·`GraphQlExtensionsPolicy` 대상. API surface 재승인(163→161) | - | 두 타입을 삭제하고 테스트는 실제 경로(`GraphQlPlatformWebInterceptor.verifyRequestBounds`, `GraphQlRequestSize`, `GraphQlJsonStructurePolicy`) 대상으로 옮김 |
| J-10e | Consider | 두 번째 에러 어휘: 요청 단계 거부가 `GraphQlWireErrorMapper`를 거치지 않아 `ApiErrorCarrier`가 `INTERNAL_ERROR`로 바뀜 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 호출부 전환은 Wave 2 NEW-9a에서 이미 됨(`runtime/GraphQlPlatformWebInterceptor.java:169`, `runtime/GraphQlPlatformInstrumentation.java:91`이 주입된 `GraphQlWireErrorMapper.toGraphQlError` 사용). 이번에 매퍼를 `error/GraphQlWireErrorMapper.java`로 옮기고 `GraphQlPlatformRejectionMapper`를 없애 경로가 정말 하나다. 기존 `GraphQlRequestStageErrorMappingTest` PASS | - | 두 호출부를 `GraphQlWireErrorMapper`(bean 주입)의 요청 단계 메서드로 바꿔 필드·요청 단계가 같은 mapper를 쓰게 |
| J-10f | Consider | `GraphQlPlatformActuatorEndpoint`·`…ConfigurationReport`가 bean이 아님 | 해당 없음(코드 삭제) | 제거 표 「`GraphQlPlatformActuatorEndpoint`, `GraphQlPlatformConfigurationReport`」 | - | - |
| J-10g | Consider | `schema/` 19개 중 16개 도달 불가 | 해당 없음(코드 삭제) | 제거 표 「schema gate·병렬 조립기 … 14개」. 남은 `schema/` 3개(`GraphQlScalar*`)는 자동 설정에서 도달 | - | - |
@@ -481,7 +482,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| K-10a | Consider | gRPC 인증 정책이 yes/no만 반환해 식별자를 `Context`로 넘기지 못함 | 완료 | Wave 3 W3-P17 (Wave 3 라운드 1 커밋): `119b25b7`. `GrpcAuthenticationPolicy`가 `Optional<Principal> authenticate(Metadata)`(`src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcAuthenticationPolicy.java:20`), 인터셉터가 `Context.Key`에 담아 `Contexts.interceptCall`(`GrpcAuthenticationInterceptor.java:40`), handler는 새 `GrpcAuthenticatedCaller.current()`로 읽는다. `null` 반환은 fail-closed. status/trailer 매핑(`call.close(...)`·`GrpcStatusMapper`)은 바꾸지 않았다(P15 영역). 테스트: `GrpcP1BoundaryWireTest.theAuthenticatedCallerReachesTheFeatureHandlerThroughTheGrpcContext`(실제 loopback Netty로 handler가 principal 이름을 응답), `GrpcAuthenticationInterceptorTest.aPolicyReturningNullIsRejectedAsUnauthenticated`. API 변경이라 FAIL 단계는 컴파일 실패(구 `isAuthenticated` 계약에 식별자 경로 없음). `:adapter:inbound:grpc:check`·`grpcTransportQualificationTest` 통과. CLAUDE.md·README 문구 갱신 | - | `Optional<Principal> authenticate(Metadata)`로 바꾸고 인터셉터가 `Context.Key`에 담아 `Contexts.interceptCall` |
| K-10b | Consider | gRPC 인증 정책 예외를 로그 없이 삼킴 | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): `GrpcAuthenticationInterceptorTest.aThrowingPolicyIsLoggedWithItsTypeAndMethodButNotItsMessage` FAIL(출력 `""`)→PASS. 예외 타입·메서드만 WARN, 메시지(자격 증명 가능)는 남기지 않음 `src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcAuthenticationInterceptor.java:44`. 커밋 `a498ad84` | - | 예외 타입·메서드명만 WARN 로그(자격 증명 제외) 후 UNAUTHENTICATED |
| K-11a | Consider | live STOMP inbound/outbound 채널 executor queue가 무제한(`Integer.MAX_VALUE`) | 완료 | Wave 1–2 P5 (fcddab7e·Wave 2 커밋): `WebSocketAutoConfigurationTest.clientChannelExecutorsAreBoundedByTheConfiguredQueueCapacity` FAIL(`[(2147483647, false), (2147483647, false)]` ≠ `[(64, true), (64, true)]`)→PASS. inbound·outbound 둘 다 스레드 CPU×2 고정(core=max), 큐 `app.websocket.channel-queue-capacity`(기본 10000, `@Positive`) `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java:74,83`, `.../stomp/WebSocketSettings.java:32`. 새 env 키 `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY`(`docs/registries/env-keys.yaml`, `src/.env.example`), `verifyEnvKeys` 통과. 커밋 `b39d3de0` | - | `registration.taskExecutor().corePoolSize/maxPoolSize/queueCapacity(n)`을 inbound·outbound 둘 다 설정(`WebSocketSettings`에서 값) |
| K-11b | Consider | 동기 `@EventListener` 브로드캐스트가 구독자 수만큼 발행 스레드에서 fan-out | 남음 | `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/LiveEventStompBroadcaster.java:57-87` | W3 | best-effort(R1) 문서 기준이면 브로커 채널에 executor를 두거나(`configureMessageBroker`의 `brokerChannel` taskExecutor) 리스너를 비동기로 |
| K-11b | Consider | 동기 `@EventListener` 브로드캐스트가 구독자 수만큼 발행 스레드에서 fan-out | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `WebSocketConfig.configureMessageBroker`에서 `bounded(registry.configureBrokerChannel())`(`websocket/.../stomp/WebSocketConfig.java:102`) — simple broker fan-out이 발행 스레드가 아니라 bounded executor에서, 큐가 차면 broadcaster가 drop(R1). `WebSocketAutoConfigurationTest.brokerChannelFansOutOnItsOwnBoundedExecutorInsteadOfThePublishingThread` FAIL(`Expecting actual not to be null` — broker channel executor 없음)→PASS | - | best-effort(R1) 문서 기준이면 브로커 채널에 executor를 두거나(`configureMessageBroker`의 `brokerChannel` taskExecutor) 리스너를 비동기로 |
| K-12a | Nit | `moduleboundary/WebSocketStableModule` `HANDSHAKE` Javadoc 중복 | 해당 없음(코드 삭제) | 제거 표 「websocket main의 검증용 코드(`moduleboundary`, `evidence`, `release`)」 | - | - |
| K-12b | Nit | websocket `CLAUDE.md`가 Boot 4.0.0 표기 | 완료 | `src/adapter/inbound/websocket/CLAUDE.md:8` "Spring Boot 4.0.8"(`208077fd`은 4.0.0). 커밋 `6d27356e` | - | - |
| K-12c | Nit | gRPC `CLAUDE.md`가 Boot 4.0.0 표기 | 남음 | `src/adapter/inbound/grpc/CLAUDE.md:8` | W5 | 버전 숫자를 지우고 "버전은 version catalog가 정본"으로(같은 문구가 `src/adapter/inbound/graphql/CLAUDE.md:8`에도 있음) |
@@ -717,7 +718,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| X1-#6c | Required | app-core inbox 삭제로 `IdempotencyOwner`·`InboxOwner` 중복 record 해소 | 해당 없음(코드 삭제) | `application/inbox/` 삭제(`docs/capability-status.md:155`) | - | - |
| X1-#6d | Required | `ClaimFencingContract` kit를 application-core testFixtures에 두고 row lease store마다 실행 | 남음 | outbox 전용 `OutboxLeaseFencingContract`만 있음. durable operation(`claimNext`·`heartbeat`), notification `JpaRecipientLeaseStore`는 공통 fencing kit 없음 | W4 | `OutboxLeaseFencingContract`의 "밀려난 쪽 종결 쓰기는 0건" 시나리오를 범용 `ClaimFencingContract`로 올리고 durable operation·recipient lease store 2곳에 상속 추가 |
| X1-#6e | Required | notification `recipients.save`가 lease 확인 없이 씀 (= B-5) | 완료 | Wave 1–2 P3 (fcddab7e·Wave 2 커밋): B-5a·B-5b와 같은 결함. 같은 수정·테스트(`DispatchOutcomeRecorder.java:122,153`) | - | projection 뒤 recipient를 다시 읽고 recorder 소유 필드만 `saveHeldBy(lease)`로 기록 + late-match 회귀 테스트 |
| X1-#6f | 권고 | shared-contract `OperationalRecordStorePort`(CAS 저장 포트) 사용처 0 — 리뷰 권고 "미사용분 삭제" 적용 대상 | 남음 | `shared-contract/.../opstore/OperationalRecordStorePort.java:19`, 같은 패키지 `OperationalRecord`·`OperationalRecordConflictException` 포함 구현·호출·테스트·문서 참조 0(`git grep -w OperationalRecordStorePort` → 자기 파일뿐) | W3 | `shared-contract/src/main/java/dev/caskeleton/shared/opstore/` 3개 삭제, `docs/capability-status.md` 제거 표에 한 줄 |
| X1-#6f | 권고 | shared-contract `OperationalRecordStorePort`(CAS 저장 포트) 사용처 0 — 리뷰 권고 "미사용분 삭제" 적용 대상 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `shared/opstore/` 3개 삭제 | - | `shared-contract/src/main/java/dev/caskeleton/shared/opstore/` 3개 삭제, `docs/capability-status.md` 제거 표에 한 줄 |
| X1-#7a | Required | readiness 카드 스키마 3개·검증기 3개, family별 evidence plugin | 남음 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): 위 행과 같은 작업. JPA 검증기는 leaf 테스트로 옮김, messaging 검증기 이동은 같은 사유로 결정 필요. 승인자: 저장소 소유자 결정 필요<br>결정 29·31(2026-09-28): 보류 해제 → 남음, 빌드 잔여 묶음 P27 | W3 | 결정(2026-09-25): O3 방향(X1-지도-readiness와 같은 작업) |
| X1-#7b | Required | API-surface gate 3개 → `ca.api-surface` 하나 | 완료 | notification·persistence-jpa·persistence-mongo·graphql 모두 `id 'ca.api-surface'`(`adapter/outbound/notification/build.gradle:4`, `persistence-jpa/build.gradle:7`), `ca.notification-api-surface`·`verifyJpaAdopterApiSurface` 삭제. JPA adopter import 검사는 leaf 테스트 `JpaAdopterApiSurfaceTest`, 커밋 `6d27356e` | - | - |
| X1-#7c | Required | web·graphql·websocket main의 moduleboundary 3벌 → ArchUnit | 완료 | 3벌 삭제(`docs/capability-status.md:80,93,113`), graphql 규칙 2개는 `GraphQlTransportBoundaryArchitectureTest.java`로, 커밋 `6d27356e` | - | - |
@@ -779,7 +780,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S1-#4 | Required | `NotificationDispatchService` 생성자 15개, record 필드별 재조립·실패 분류가 한 클래스에 (B-5 구조 원인) | 남음 | `application-notification/.../dispatch/NotificationDispatchService.java:72`(인자 15개), `:208`·`:485` record 재조립, `:255-288` catch 분기, `:475`·`:513` 종료 상태 두 번 계산. `DispatchOutcomeRecorder.java:67,110` 재조립 2곳 | W3 | `DeliveryAttemptRecord.completed(result, at)`·`RecipientDeliveryRecord.advancedRoute(now)` 전이 메서드 추가, catch 분기는 `ProviderOutcomeClassifier` 정적 메서드로 분리 |
| S1-#5 | Required | fileserver retire 절차 3곳 복사, admin `forceDelete`는 content 없는 레코드를 DELETING에 남김 (C-4 관련) | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): `FileserverAdminServiceTest.forceDeletingAFileThatWasNeverPublishedRetiresItCompletely` FAIL(`expected: DELETED but was: DELETING`)→PASS. 세 호출부가 `src/application-fileserver/.../cleanup/FileRetirement.java:40` 하나를 쓴다: `DefaultFileLifecycleService.java:84`, `DefaultFileserverAdminService.java:167`, `DefaultUploadApplicationService.java:265`. `cleanup` 패키지에 둔 이유: 세 호출 패키지가 이미 cleanup을 의존하고 cleanup은 그들을 의존하지 않아 새 패키지 순환이 생기지 않는다 | - | `retire(FileRecord)` 하나로 합치고 content 없으면 DELETING→DELETED 전이를 세 호출부 모두에 적용 |
| S1-#6a | Required | fileserver 단일 구현 인터페이스 6개(fake 없음) | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `1ec8f087`·`8e731b9f`. 구현 1개·대역 0인 `WriterLeaseCoordinator`·`TransferAdmissionController` 인터페이스를 지우고 `Default*`가 그 이름을 가짐, `FileStateMachine`은 S1-#13으로 삭제. 수정 방향과 다르게 남긴 3개와 이유: `FileLifecycleService`는 web-fileserver `FileLifecycleController`가 부르는 inbound 포트라 `INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES`(architectureTest)가 구체 클래스 의존을 금지(없앴다가 architectureTest FAIL로 복원), `CleanupService`·`FileReconciliationService`는 composition `FileserverCleanupWorkerTest`·`FileserverStructuredLoggingTest`가 람다/익명 대역으로 구현(두 번째 구현 존재 — 현황표 근거 "fake 없음"이 틀림). `FileserverUseCaseContractDeviationTest.KNOWN_DEVIATIONS` 갱신 | - | 인터페이스 6개 삭제, `Default*`를 인터페이스 이름으로 개명 |
| S1-#6b | Required | fileserver 인바운드가 use-case 계약 밖(capability gate 미적용) | 보류 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): 사유: 결정 필요 — transport 연산 약 30개를 `CommandUseCase`/`QueryUseCase` + `@UseCaseCapability`로 바꾸면 `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`(architectureTest) 때문에 쓰기 연산마다 `@RequiresPermission("file:…")`이 필요하고, 그 annotation은 web `RequiresPermissionAuthorizationManager`가 `AuthorizationPort`로 런타임에 강제한다. 즉 기존 `FileAccessPolicyPort`(역할·소유자 검사, C-8a) 위에 권한 게이트가 하나 더 생기고, 배포는 새 권한 이름을 부여해야 기존 업로드·다운로드가 계속 된다. (1) fileserver 연산에 method-security 권한을 추가할지(추가하면 권한 이름 체계), 아니면 (2) `RepositoryAccess`/권한 규칙에서 fileserver를 예외로 둘지를 정해야 한다(`docs/fileserver/design-deviations.md` §5가 ADR로 열어 둔 질문). 승인자: 저장소 소유자 결정 필요 | W3 | transport가 부르는 연산을 `*UseCase` + `@UseCaseCapability`로 선언 |
| S1-#6b | Required | fileserver 인바운드가 use-case 계약 밖(capability gate 미적용) | 남음 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): 사유: 결정 필요 — transport 연산 약 30개를 `CommandUseCase`/`QueryUseCase` + `@UseCaseCapability`로 바꾸면 `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`(architectureTest) 때문에 쓰기 연산마다 `@RequiresPermission("file:…")`이 필요하고, 그 annotation은 web `RequiresPermissionAuthorizationManager`가 `AuthorizationPort`로 런타임에 강제한다. 즉 기존 `FileAccessPolicyPort`(역할·소유자 검사, C-8a) 위에 권한 게이트가 하나 더 생기고, 배포는 새 권한 이름을 부여해야 기존 업로드·다운로드가 계속 된다. (1) fileserver 연산에 method-security 권한을 추가할지(추가하면 권한 이름 체계), 아니면 (2) `RepositoryAccess`/권한 규칙에서 fileserver를 예외로 둘지를 정해야 한다(`docs/fileserver/design-deviations.md` §5가 ADR로 열어 둔 질문). 승인자: 저장소 소유자 결정 필요<br>결정 32(2026-09-28): 권한 추가로 결정 → 남음, P28 | W3 | transport가 부르는 연산을 `*UseCase` + `@UseCaseCapability`로 선언 |
| S1-#7 | Consider | 에러 코드마다 예외 서브클래스, 타입 분기는 몇 개뿐 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `6d6c69fe`. `FileserverException`을 구체 클래스로(`api/error/FileserverException.java:37` `of(code, message)`, `notReady(fileId, state)`). catch/instanceof로 타입 분기하는 5개(`FileNotFoundException`·`FileAlreadyExistsException`·`InvalidPathException`·`UploadOffsetMismatchException`·`AmbiguousCompletionException`)만 남기고 17개 삭제, 생성 지점 약 110곳을 `new FileserverException(message, context)`/`FileserverException.of(CODE, …)`로. 테스트의 타입 분기(`MvcUploadExecutorSaturationTest`, PG `aReleasedReservationCanNeverBeCommittedOrExtended`)는 `code()` 비교로. fileserver 5개 leaf `check`·PG lane 3개 PASS | - | base를 구체 클래스 + `of(code, …)`, 서브클래스는 catch로 타입 분기하는 5개만 남김 |
| S1-#8 | Consider | `PolicyTransactionPort` 계열이 호출 1곳용 | 해당 없음(코드 삭제) | 「제거된 코드」 `PolicyTransactionPort` 계열·`SpringPolicyTransactionPort`·`FileserverCompensationTransaction` 행. grep 0건 | - | - |
| S1-#9 | Consider | 같은 전략만 담은 레지스트리 2개 | 남음 | `application-notification/.../callback/ProviderEventProjectorRegistry.java:7`(Twilio/Ses projector는 `StandardDeliveryProjector` 상속만), `dispatch/TemplateRendererRegistry.java:7` + `adapter/outbound/notification/.../NotificationPlatformProviderConfig.java:57-65`(모든 channel에 같은 engine) | W3 | 레지스트리·`Map*Registry` 삭제, 구현체 직접 주입 |
@@ -790,14 +791,14 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S1-#13 | Consider | `FileStateMachine` 인터페이스+구현+bean이 전이표 Map 하나 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `1ec8f087`. `FileState.canTransitionTo`/`requireTransitionTo`(`api/FileState.java:40`), `FileStateMachine`·`DefaultFileStateMachine`·bean(`FileserverVerificationConfiguration`, PG 테스트 context) 삭제, `JpaFileMetadataStore` 생성자에서 인자 제거. `FileStateTransitionTest.everyStatePairMatchesTheDesignTransitionTable` PASS | - | `FileState.canTransitionTo(target)` enum 메서드로 대체 |
| S1-#14 | Consider | notification platform 미사용 약 920줄(예외 12, security 3, sms/push/email/webpush) (= B-8) | 해당 없음(코드 삭제) | 「제거된 코드」 notification `sms`·`push`·`email`·`webpush` facade, throw 0 예외 12종, redaction 5종 행. 해당 디렉터리 없음 확인 | - | - |
| S1-#15a | Consider | shared-contract `activation/*`(bootstrap만 사용) | 해당 없음(코드 삭제) | 「제거된 코드」 `MasterSwitch`·`MasterSwitchParser`(shared-contract `activation` 전체) 행 | - | - |
| S1-#15b | Consider | shared-contract `opstore/*` 구현·소비자 0 | 남음 | `shared-contract/.../opstore/OperationalRecordStorePort.java` 외 2개, shared-contract 밖 참조 0(graphql `advanced/**` 삭제 뒤) | W3 | `opstore` 패키지 삭제 |
| S1-#15b | Consider | shared-contract `opstore/*` 구현·소비자 0 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`(X1-#6f와 같은 삭제) | - | `opstore` 패키지 삭제 |
| S1-#15c | Consider | ratelimit 정책 타입이 cache-redis 전용 | 남음 | `shared-contract/.../ratelimit/RateLimitPolicy`·`RateLimitAlgorithm` main 소비자는 cache-redis뿐, `RateLimitEvaluationDedupPolicy`는 테스트만 참조 | W3 | 세 타입을 `adapter:outbound:cache-redis`로 이동(`EdgeRateLimitPort` 계열만 shared에 유지) |
| S1-#15d | Consider | shared-contract CLAUDE.md 책임 목록이 패키지 일부만 설명 | 남음 | `shared-contract/CLAUDE.md:17-30`은 response·error·request·health·tracing만, 실제 패키지 15개(annotation·concurrency·headers·metrics·operation·registry·runtime·security·ratelimit·opstore 누락) | W5 | 책임 목록을 현재 패키지 기준으로 갱신 |
| S1-#16 | Consider | 문서가 말하는 `application-core → domain-core` 의존이 빌드에 없음 | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): `src/application-core/build.gradle` `implementation project(':domain-core')` 복원(registry 허용 edge). `architectureCheck` PASS. 같은 행의 `NotificationIdGeneratorPort`·`UploadIdentifierFactory` → `IdFactory` 정리는 application-notification/fileserver·persistence-jpa·composition을 바꾸는 작업이라 하지 않음(P16-new-5) | - | `application-core/build.gradle`에 `implementation project(':domain-core')` 복원, `NotificationIdGeneratorPort`·`UploadIdentifierFactory`를 `IdFactory` 기반으로 정리 |
| S1-#17a | Consider | objectstorage 식별자 클래스 6개·가드 2개 복사 | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `7a21c6e7`. `ObjectId`·`ObjectReference`·`ObjectStageHandle`·`ObjectVersionToken`을 compact constructor + `toString`(redacted) record로(`identity/ObjectId.java:4`). `DirectTransferSessionId`·`PartReceiptToken`은 D-7a에서 이미 삭제. 가드는 `ObjectModelSupport.requireBoundedToken`(`model/ObjectModelSupport.java:9`) 하나, `ObjectRequestSupport.boundedToken` 삭제. `:application-objectstorage:check`, control record 골든 digest(`ObjectControlRecordCodecTest`) PASS | - | 식별자를 record + `toString` 재정의로, 가드는 하나로 |
| S1-#17b | Consider | legacy `application.storage` 네임스페이스 공존(Javadoc 모순) | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `e8b6bae0`. sample에는 이미 canonical 포트 위의 `PublishPosterImageUseCase`(mode=publication)가 있어 legacy mode(`UploadPosterImageUseCase`·`LegacyPosterImageController`)를 지우고 local/test profile은 `mode: disabled`. `application.storage.ObjectStoragePort`·`StoredObject`와 legacy 어댑터 2개 삭제. `:sample-portfolio:check`·`systemTest` PASS | - | 「한 기능에 한 세대」: sample `UploadPosterImageUseCase`를 `application.objectstorage` 포트로 옮기고 legacy 포트·어댑터 2개 삭제 |
| S1-#18a | Consider | `V2` 접미사 타입 | 완료 | `6d27356e`: 멱등성 V2 → 무접미사, outbox V2 삭제. main의 `*V2*.java`는 sample 이벤트 스키마 버전 `PosterImageAttachmentReadyV2` 하나뿐 | - | - |
| S1-#18b | Consider | 포트·서비스 이름 규칙이 leaf마다 다름 | 보류 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): outbound 부분은 완료(`18ed5e7d`): `FileQuotaService`→`FileQuotaPort`, `FileMetadataStore`→`FileMetadataPort`, `UploadSessionStore`→`UploadSessionPort`, `*Gateway` 8개→`*Port`, 그 밖의 outbound 포트 9개에 `Port` 접미사(어댑터 구현 이름은 유지). 남은 inbound `*Service`→`*UseCase` 개명은 S1-#6b와 같은 결정에 묶인다 — 이름이 `UseCase`로 끝나고 `TransactionPort`를 쥔 클래스는 `ORCHESTRATION_ENTRYPOINTS_DECLARE_A_CAPABILITY`로 `@UseCaseCapability`가, 쓰기면 `@RequiresPermission`이 필요하다. 승인자: 저장소 소유자 결정 필요(S1-#6b와 함께) | W3 | 소유자 규칙대로 outbound `*Port`, inbound `*UseCase`로 기계적 개명 |
| S1-#18b | Consider | 포트·서비스 이름 규칙이 leaf마다 다름 | 남음 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): outbound 부분은 완료(`18ed5e7d`): `FileQuotaService`→`FileQuotaPort`, `FileMetadataStore`→`FileMetadataPort`, `UploadSessionStore`→`UploadSessionPort`, `*Gateway` 8개→`*Port`, 그 밖의 outbound 포트 9개에 `Port` 접미사(어댑터 구현 이름은 유지). 남은 inbound `*Service`→`*UseCase` 개명은 S1-#6b와 같은 결정에 묶인다 — 이름이 `UseCase`로 끝나고 `TransactionPort`를 쥔 클래스는 `ORCHESTRATION_ENTRYPOINTS_DECLARE_A_CAPABILITY`로 `@UseCaseCapability`가, 쓰기면 `@RequiresPermission`이 필요하다. 승인자: 저장소 소유자 결정 필요(S1-#6b와 함께)<br>결정 32(2026-09-28): 권한 추가로 결정 → 남음, P28 | W3 | 소유자 규칙대로 outbound `*Port`, inbound `*UseCase`로 기계적 개명 |
| S1-#19 | Nit | 이력 주석·inline FQN | 남음 | 재측정: 이력 문구("used to" 등) application-core 14·notification 23·fileserver 9·objectstorage 1줄, notification inline FQN 74줄 | W5 | 불변 조건 1~2줄만 남기고 이력은 git/ADR로, FQN은 import로 |
| S1-#20 | Nit | notification `dispatch/` 패키지에 여러 기능 | 남음 | `application-notification/.../platform/dispatch/` 46파일 3,855줄(제출·템플릿 게시·`ContactPoint*`·reconciliation 포함) | W5 | `submission/`, `dispatch/`, `reconciliation/`로 이동, `ContactPoint*`는 `contact/`로 |
| S1-lead-1 | 권고 | messaging 자체 outbox/inbox와 app-core outbox/inbox가 같은 패턴 3~4벌 | 완료 | app-core inbox 삭제(「제거된 코드」 same-store inbox 행), outbox V2 삭제. 남은 2벌(app outbox + vendored `messaging_outbox`)은 D2 결정(`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md:104` "messaging platform outbox는 vendored라 유지") | - | - |
@@ -925,7 +926,7 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S5-#6b | Required | 호출처 0인 `mapRequestRejection`과 참조 0인 error 클래스 | 완료 | `mapRequestRejection`·`GraphQlRequestErrorMapper`·`GraphQlSubscriptionExceptionResolver`·`GraphQlNullabilityContract` grep 0건. 표 "`GraphQlWireErrorMapper.mapRequestRejection`" 행과 `error/` 행 | - | - |
| S5-#6c | Required | Category switch 3개와 client 문구 중복 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): switch 3개(`category`·`clientMessage`·`classificationOf`)를 `error/GraphQlWireErrorMapper.java:43` `RENDERINGS`(Category → wire category·ErrorType) 하나와 shared 문구 표로 대체. "요청한 리소스를 찾을 수 없습니다." 3곳은 모두 `ClientErrorMessages.of(NOT_FOUND)` 한 곳에서 온다(`GraphQlAuthorizationInterceptor.toWireError`는 `fromRejection` 위임). graphql `check`·`systemTest`·`graphqlTransportQualificationTest` PASS | - | `EnumMap<Category, Rendering(wireCategory, message, classification)>` 표 하나로 switch 3개를 대체하고 문구 상수를 한 곳에 둔다 |
| S5-#6d | Required | 플랫폼 예외 `instanceof` 사슬 9개, 실제 매퍼가 `runtime/`에 있음 | 완료 | Wave 3 W3-P15 (Wave 3 라운드 1 커밋): 플랫폼 예외 11종이 `error/GraphQlPlatformRejection` 구현, instanceof 사슬(`GraphQlPlatformRejectionMapper`) 삭제, `GraphQlWireErrorMapper`·`GraphQlWireErrors`를 `runtime/`→`error/`로 이동(테스트도 이동). API surface 재승인(`updateGraphQlApiSurface -PapproveGraphQlApiSurfaceChange`) | - | 플랫폼 예외가 code·category·message 인터페이스를 구현하게 해 instanceof 사슬을 없애고, 매퍼 3개를 `error/`로 옮긴다 |
| S5-#7a | Consider | `GraphQlPlatformAutoConfiguration` 한 클래스에 bean 약 40개·10가지 기능 | 남음 | `graphql/…/autoconfigure/GraphQlPlatformAutoConfiguration.java` 656줄(706→656), `@Bean` 38개. FQN `@org.springframework.context.annotation.Configuration`(`:78`) | W3 | 기능별 `@Configuration`(검증·runtime 감지·body limit·chain·auth·cost·error·관측·cache·DataLoader)으로 나누고 `GraphQlRootAutoConfiguration`의 `@Import`에 나열 |
| S5-#7a | Consider | `GraphQlPlatformAutoConfiguration` 한 클래스에 bean 약 40개·10가지 기능 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `GraphQlPlatformAutoConfiguration`(38 bean)을 기능별 package-private `@Configuration` 8개로 분해: `GraphQlRequestContextConfiguration`·`GraphQlExecutionChainConfiguration`·`GraphQlErrorConfiguration`·`GraphQlScalarConfiguration`·`GraphQlObservationConfiguration`·`GraphQlPreparsedCacheConfiguration`·`GraphQlDataLoaderConfiguration`·`GraphQlRequestBodyLimitConfiguration`. `GraphQlPlatformAutoConfiguration`은 startup 검증 + anonymous 상수만. `GraphQlRootAutoConfiguration.java:27` `@Import`에 나열. 새 클래스는 package-private이라 API surface 변화 없음. graphql `test`·`systemTest`·`graphqlTransportQualificationTest` PASS | - | 기능별 `@Configuration`(검증·runtime 감지·body limit·chain·auth·cost·error·관측·cache·DataLoader)으로 나누고 `GraphQlRootAutoConfiguration`의 `@Import`에 나열 |
| S5-#7b | Consider | 부팅마다 reflection 아키텍처 검사(`architecture/` 969줄) | 완료 | `architecture/` 삭제, `graphQlControllerBoundaryCheck` bean 삭제(표 110·111행). 규칙 2개는 `graphql/src/test/…/GraphQlTransportBoundaryArchitectureTest.java`(ArchUnit)로 옮김 | - | - |
| S5-#7c | Consider | autoconfig Javadoc이 사실과 다름 | 남음 | `GraphQlPlatformAutoConfiguration.java:70-76`은 "A real @AutoConfiguration … ordered after Spring Boot's GraphQL auto-configuration"이라고 적었지만 클래스는 `@Configuration`이고, `GraphQlRootAutoConfiguration`에는 `after` 선언이 없음. `GraphQlRootAutoConfiguration.java:29-30` 주석은 이미 삭제된 "scan 제외 정규식"을 전제로 함 | W5 | Javadoc을 실제 구조(root `@AutoConfiguration`이 import)에 맞추고, 순서가 필요하면 root에 `afterName`을 추가. 낡은 scan 주석 삭제 |
| S5-#8 | Consider | web이 하위 leaf 패키지 구조를 앎(`moduleboundary`) (= X1-7) | 완료 | web·graphql `moduleboundary` 디렉터리, `WebStableModule`, `WebBuildModel` grep 0건. 표 93·113행 | - | - |
@@ -976,18 +977,18 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| S6-#6a | Required | 멱등성 설정 binder 3개·yml 2개, PG provider 하드코딩 (= X1-#2) | 완료 | settings record 하나 `IdempotencySettings`(`BS/autoconfigure/idempotency/IdempotencySettings.java:24-34`, prefix `ca-skeleton.capabilities.idempotency`), `config/idempotency.yml`·`IdempotencyProviderSettings`·`PostgreSqlIdempotencyProviderConfig` 삭제(`CS:228`), `APP_IDEMPOTENCY_TTL` 한 키(`src/app-bootstrap/src/main/resources/config/capabilities.yml:14`) | - | - |
| S6-#6b | Required | `APP_RATE_LIMIT_DEFAULT_POLICY_ID`가 두 키에 바인딩 | 완료 | Wave 1–2 P6 (fcddab7e·Wave 2 커밋): 두 키 모두 읽히고 있었다(web `EdgeRateLimitTransportSettings`가 `app.rate-limit.*`, cache-redis `RedisRateLimitConfig`가 `ca-skeleton.capabilities.rate-limit.default-policy-id`). 소유자 결정 16(`app.*` 통일)에 맞춰 `app.rate-limit.default-policy-id` 하나만 남김: `cache-redis.yml:65` 줄과 `RedisCapabilitySettings.RateLimit.defaultPolicyId` 삭제, `RedisRateLimitConfig.java:34,60`이 `app.rate-limit.default-policy-id`로 검증. env 키 `APP_RATE_LIMIT_DEFAULT_POLICY_ID`는 그대로(`env-keys.yaml`·`.env.example` 변경 없음). `RedisCapabilityCompositionTest.aDefaultPolicyTheLimiterDoesNotHaveIsRefusedAtStartup` FAIL(`Expecting actual not to be null`)→PASS | - | 읽는 쪽 하나만 남기고 다른 키 삭제(sample의 `ca-skeleton.rate-limit.*`는 1차 L-11) |
| S6-#7 | Required | sample이 bootstrap 인프라를 복사, 이미 갈라짐 | 남음 | `SP/bootstrap/{tracing,idempotency,settings,logging,metrics,context,management}` 525줄. `SampleTracingSampleRateResolver.java:23` `"staging" -> 0.10`, `SampleIdempotencyConfig.java:15` "stand-in", `SamplePseudonymizationConfig.java:12` "Sample-local copy" | W3 | 소유자 결정대로 멱등성 executor·outbox relay 조립을 `composition:*` 모듈로 옮겨 두 root가 함께 쓰고, tracing·logging·metrics·context·management는 공용 library leaf로(registry edge 추가), staging 분기 삭제 |
| S6-#8 | Required | sample root가 다른 leaf 패키지를 넓게 scan | 남음 | `SP/SamplePortfolioApplication.java:31-60`: `@ComponentScan`·`@ConfigurationPropertiesScan`에 `adapter.inbound.web`, `adapter.outbound.identifier`, `adapter.outbound.objectstorage`, `application`, `domain`, `shared`. JPA만 auto-config로 바뀜 | W3 | scan을 `dev.caskeleton.sample`로 좁히고 web·identifier·objectstorage는 각 leaf auto-config로 받기(보안 설정 2개는 exclude/property로 끔) |
| S6-#8 | Required | sample root가 다른 leaf 패키지를 넓게 scan | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `SamplePortfolioApplication`: `@ComponentScan("dev.caskeleton.sample")`·`@ConfigurationPropertiesScan("dev.caskeleton.sample")`, 제외는 `WebSecurityAutoConfiguration` 하나(`SamplePortfolioApplication.java:31-32`). web·objectstorage는 각 auto-config로. `SamplePublicAccessSecurityConfigTest.sampleCompositionRootExcludesOnlyTheWebSecurityRoot`·`sampleCompositionRootScansOnlyTheSamplePackage`(옛 exclude-filter 단언 대체). sample `test`·`integrationTest` 51·`systemTest` 3·`webSystemTest` 5 PASS | - | scan을 `dev.caskeleton.sample`로 좁히고 web·identifier·objectstorage는 각 leaf auto-config로 받기(보안 설정 2개는 exclude/property로 끔) |
| S6-#9 | Required | sample `application.yml` 중 읽는 코드 없는 블록 | 남음 | 326줄 중 약 101줄: `src/sample-portfolio/src/main/resources/application.yml:150-177`(capabilities.cache), `:180-181`(bootstrap), `:210-226`(logging), `:255-279`(app.cache.redis), `:280-283`(messaging), `:284-288`(notification), `:289-308`(outbound.http). sample classpath에 해당 binder 없음(`src/sample-portfolio/build.gradle:48-83`) | W5 | 해당 블록 삭제 |
| S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 남음 | poster 관련 main 약 5.9k줄 vs WorkLog 약 2.2k줄. `SP/application/`에 `command/query/event/port/exception`과 `poster/posterimage/worklog` 공존 | W3 | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 |
| S6-#10b | Consider | poster-image legacy API 모드 | 남음 | `SP/adapter/inbound/web/controller/LegacyPosterImageController.java:23`(`mode=legacy`), `SP/domain/poster/LegacyPosterImageAttachment.java`, `SP/application/poster/UploadPosterImageUseCase.java` | W3 | legacy 모드와 전용 타입 삭제 |
| S6-#10c | Consider | 상태 머신이 application 계층, use case 생성자 14개 | 남음 | `SP/application/posterimage/PosterImageUploadIntent.java`(333줄), `SP/application/poster/PublishPosterImageUseCase.java:77-91`(인자 14개) | W3 | 상태 머신을 domain으로, 설정값 인자(TTL·lease·epoch·destination)를 record 하나로 |
| S6-#10d | Consider | `WorkLogSortField`(domain)가 HTTP 이름과 persistence 이름을 같이 앎 | 남음 | `SP/domain/worklog/WorkLogSortField.java:11-23`(`property` 하나로 `fromRequest` 매칭) | W3 | 요청 이름 매핑은 web mapper로, persistence 이름은 persistence mapper로; domain enum은 논리 필드만 |
| S6-#10a | Consider | sample 대표 예제가 poster-image에 묻힘, 패키지 종류별·기능별 혼재 | 남음 | poster 관련 main 약 5.9k줄 vs WorkLog 약 2.2k줄. `SP/application/`에 `command/query/event/port/exception`과 `poster/posterimage/worklog` 공존<br>Wave 3 W3-P25: 미완 — 이유: 기능별 패키지 재배치와 poster-image 별도 sample 모듈 분리는 sample 전체 파일 이동(+`modules.json` leaf 등록)이라, 동시에 도는 P18(sample outbox·멱등성·`PosterEventPublisher`)·P24(object storage)와 같은 파일을 대량으로 겹친다. 통합 뒤 단독 작업으로 넘김. 이번 묶음에서 legacy 모드 삭제(S6-#10b)로 poster 표면은 줄었다 | W3 | 기능별 패키지로 정리, poster-image는 objectstorage 검증용 별도 sample 모듈로 이동 |
| S6-#10b | Consider | poster-image legacy API 모드 | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`: `LegacyPosterImageController`·`UploadPosterImageUseCase`·`UploadPosterImageCommand`·`LegacyPosterImageAttachment`·`PosterImageApiConfig`·`PosterImageApiSettings`(LEGACY 모드)·`Poster.attachImage`·`Poster.imageKey()`·dual-read `rehydrate` 삭제. `PosterEntity`는 `image_key`를 매핑하지 않고, CAS attach가 `image_key = NULL`로 pre-V8 행을 정규 경로로 받는다(`PosterImageAttachmentCasRepository.java:32`). `PosterRepositoryAdapterIntegrationTest.aPreV8RawKeyRowReadsBackWithoutAnImage`·`canonicalAttachClearsAPreV8RawKeyOnTheSameRow` PASS(삭제에 따른 새 동작이라 FAIL 재현 없음). `PosterResponse.imageKey` wire 이름은 유지하고 published reference를 싣는다. sample `local` 프로필·systemTest yml의 `mode: legacy`·`object-storage.legacy` 블록 삭제 | - | legacy 모드와 전용 타입 삭제 |
| S6-#10c | Consider | 상태 머신이 application 계층, use case 생성자 14개 | 완료(부분 수정 방향 변경) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `PublishPosterImageUseCase` 설정값 인자(destination·epoch·intentTtl·handoffLease)를 `PosterImagePublicationParameters` record 하나로(생성자 14→11, 양수 검증). 상태 머신(`PosterImageUploadIntent`)의 domain 이동은 하지 않음: 필드가 `application-objectstorage`·`application-core` 값 타입(`ObjectOperationKey`, `ObjectStageHandle`, `ObjectVersionToken`, `ObjectContentIdentity`, `ObjectMediaType`, `RequestFingerprint`)이라 domain으로 옮기면 domain→application 의존이 생긴다(HARD-STOP 1과 같은 방향 위반). sample `test` PASS | - | 상태 머신을 domain으로, 설정값 인자(TTL·lease·epoch·destination)를 record 하나로 |
| S6-#10d | Consider | `WorkLogSortField`(domain)가 HTTP 이름과 persistence 이름을 같이 앎 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `WorkLogSortField`·`PosterSortField`는 논리 필드만. 요청 이름은 web mapper `SORT_FIELDS`(`WorkLogWebMapper.java:24`, `PosterWebMapper.java:19`), persistence 속성은 `sortProperty`(`WorkLogPersistenceMapper.java:57`, `PosterPersistenceMapper.java:38`). 계약 테스트·integration 51 PASS | - | 요청 이름 매핑은 web mapper로, persistence 이름은 persistence mapper로; domain enum은 논리 필드만 |
| S6-#10e | Consider | sample `CLAUDE.md` 경로 틀림, WorkLog만 설명 | 남음 | `src/sample-portfolio/CLAUDE.md:17-22`: `adapter/web`, `adapter/persistence`, `adapter/identifier`(실제 `adapter/inbound/web`, `adapter/outbound/persistence`, `adapter/outbound/identifier`) | W5 | 경로 수정, poster-image 슬라이스 한 줄 추가 |
| S6-#11a | Consider | 컨트롤러 `toId()` 4벌, sort 파싱 2벌 | 남음 | `toId`: `WorkLogController.java:239`, `PosterController.java:161`, `LegacyPosterImageController.java:49`, `PosterImagePublicationController.java:110`; sort: `WorkLogController.java:99-113`, `PosterController.java:91-105` (모두 `SP/adapter/inbound/web/controller/`) | W3 | web 어댑터 helper 하나(id 파싱, `SortParam` + enum `fromRequest` 공통 처리) |
| S6-#11a | Consider | 컨트롤러 `toId()` 4벌, sort 파싱 2벌 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `WebRequestParams`(`canonicalUuid`, `sort`) 하나로 `toId` 3벌(legacy 컨트롤러는 삭제)·sort 파싱 2벌 대체. `WebRequestParamsTest` 4건 PASS(대소문자 무시 매칭, `SORT_FIELD_NOT_ALLOWED` + 메시지, 빈 값, UUID 정규화) | - | web 어댑터 helper 하나(id 파싱, `SortParam` + enum `fromRequest` 공통 처리) |
| S6-#11b | Consider | If-Match를 컨트롤러가 update 전에 get use case로 읽어 비교(트랜잭션 밖) | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): `UpdateWorkLogCommand.expectedVersion`(`OptionalLong`, `sample-portfolio/.../application/command/UpdateWorkLogCommand.java:25`), 비교는 `UpdateWorkLogUseCase` 쓰기 트랜잭션 안(`UpdateWorkLogUseCase.java:43`, 불일치 → 새 `WorkLogVersionMismatchException` → `DomainExceptionHandler`가 412 `PRECONDITION_FAILED`). 컨트롤러는 헤더만 해석(`WorkLogController.java:211`). `WorkLogControllerWireTest.patchWithIfMatchDoesNotReadTheWorkLogOutsideTheUpdate` FAIL(`NoInteractionsWanted … GetWorkLogUseCase`)→PASS, `WorkLogUseCasesTest.staleExpectedVersionIsRefusedInsideTheUpdate`·`currentExpectedVersionAppliesTheUpdate`, `patchHandsTheIfMatchVersionToTheUpdateUseCase`, `patchWithStaleIfMatchReturns412`(유스케이스 예외 경로로 변경) PASS. 동작 변화: 여러 태그를 나열한 `If-Match`(예: `W/"1", W/"2"`)는 이제 읽지 않고 412(`patchWithAListIfMatchIsRefusedAs412`) — 이 리소스는 validator 하나만 내보냄 | - | `UpdateWorkLogCommand.expectedVersion` 추가, 비교를 update use case 트랜잭션 안으로 |
| S6-#11c | Consider | sample 테스트가 `TransactionPort` fake를 각자 작성 (= X1-#3 일부) | 완료 | application-core testFixtures `DirectTransactionPort`(`src/application-core/src/testFixtures/java/dev/caskeleton/application/transaction/testkit/DirectTransactionPort.java`), sample 테스트의 인라인 fake 0건, `6d27356e` | - | - |
| S6-#12 | Consider | JPA 정책 클래스 겸용, 주입처 없는 bean, 테스트만 쓰는 플래그 | 완료 | `JpaPlatformAutoConfiguration` 삭제·`JpaStartupAutoConfiguration`으로 합침(`CS:238`), `app.jpa-platform.addons-enabled` 삭제(`CS:193`), `jpaDataSourceProfileValidator`가 `jpaResolvedDataSourceCheck`에 주입됨(`JS/JpaStartupAutoConfiguration.java:100,109-110`), `6d27356e` | - | - |
| S6-#13 | Consider | 역할 없는 startup 예외 subclass 4개 | 남음 | `SST/{MigrationFailed,ProfileMismatch,RequiredAdapterDisabled,StartupValidation}Exception.java` — bootstrap에서 support로 옮기기만 했고 본문은 `StartupErrorCode`를 부모에 넘기기만 | W3 | `StartupFailureException` 하나 + 테스트는 `errorCode()` 단언; 생성은 `StartupFailures` factory만 |
| S6-#13 | Consider | 역할 없는 startup 예외 subclass 4개 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): 4개 subclass 삭제, `StartupFailureException`을 final + package-private 생성자로(`support/.../startup/StartupFailureException.java:18,25`), 생성은 `StartupFailures`만. 테스트 23개 파일의 `isInstanceOf(XxxException.class)`를 `isInstanceOfSatisfying(StartupFailureException.class, e -> errorCode 단언)`으로. `StartupFailureExceptionTest`는 코드→exit 파라미터 테스트. support·persistence-jpa·cache-redis·app-bootstrap `test`/`architectureTest` PASS | - | `StartupFailureException` 하나 + 테스트는 `errorCode()` 단언; 생성은 `StartupFailures` factory만 |
| S6-#14 | Consider | 스위치 prefix 3종, "capability" 뜻 여러 개 | 남음 | prefix: `ca-skeleton.*`(persistence-jpa, persistence-mongo, notification, outbox, grpc), `app.*`(messaging, redis, fileserver-platform, httpclient, object-storage, websocket), `backend.graphql`(`CS:30-45`). "capability": `@UseCaseCapability`, `capabilities.*` selector, `JpaCapability`, `MessagingCapabilities`. `MasterSwitch`·endpoint 미보고 부분은 삭제로 해당 없음 | W3 | 결정(2026-09-25): 설정 prefix를 `app.*`로 통일(`ca-skeleton.*`, `backend.graphql` → `app.*`), `APP_*` env 키 유지 |
| S6-#15 | Consider | bootstrap `:test`에 저장소 governance 테스트 | 남음 | `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/` 하위 45파일 7,302줄(`208077fd` 50파일), 이 중 34개가 저장소 파일·리소스를 직접 읽음 | W4 | `architectureTest`처럼 별도 strict lane으로 옮기고 읽는 파일을 `inputs`로 선언 |
| S6-#16a | Nit | 이력·리뷰 ID 주석 | 남음 | bootstrap main 이력/ID 줄 35개(105에서 감소, 주석 비율 19%), websocket 2개(해소 수준) | W5 | bootstrap 남은 35줄 삭제 |
@@ -1068,13 +1069,13 @@ Wave 3 라운드 1 결과로 받은 4건(2026-09-28, desktop):
| NEW-8a | Required | 알림 reconcile이 `Unsupported`면 attempt·수신자 상태를 바꾸지 않는다. 행이 영구히 남고 매 recovery 주기마다 다시 조회된다. | 완료 | Wave 1–2 P3 (fcddab7e·Wave 2 커밋): B-4b와 같은 결함. 같은 수정·테스트(`ReconciliationService.java:148`). 수정 방향대로 `ambiguousAttemptExists`·attempt는 건드리지 않아 redrive는 계속 duplicate-risk 승인을 요구 | - | `Unsupported`일 때 수신자를 운영자가 확인하는 종단 상태로 옮긴다. 예: `RECONCILIATION_REQUIRED`에 `nextCheckAt=null`, 또는 전용 `MANUAL_REVIEW` 상태. `ambiguousAttemptExists=true`를 유지하고 lease를 해제한다. 전이는 `recipients.transition(...)`을 `transactions.inWrite`로 감싸 `StillUnknown` 분기(:119-125)와 같은 모양으로 한다. |
| NEW-8b | Required | attempt가 모두 완료된 수신자가 `DISPATCHING`에 남는다(1차 리뷰 B-4). | 완료 | Wave 1–2 P3 (fcddab7e·Wave 2 커밋): B-4a와 같은 결함. 같은 수정·테스트(`LeaseRecoveryService.java:123`). 방향의 "staleAfter 지나면 reconcile 호출" 대신 requeue: 모든 attempt가 완료라 provider에 물을 것이 없고, dispatch 라우팅이 기록된 결과로 다음 단계를 정한다. `expiredDispatching`이 이미 staleAfter로 거른다 | - | `LeaseRecoveryService.recoverOnce`에서 attempt가 모두 완료인 경우를 명시적으로 처리한다. callback 대기 기한(`staleAfter`)이 지났으면 마지막 attempt로 `reconciliation.reconcile(...)`을 호출하고, 그래도 확정이 안 되면 NEW-8a의 종단 상태로 전이한다. 테스트는 attempt가 모두 완료된 DISPATCHING 행 1개로 `recoverOnce`를 두 번 부르고 상태가 바뀌는지 단언한다. |
| NEW-9a | Required | GraphQL 요청 단계 에러가 `GraphQlWireErrorMapper`를 거치지 않는다. adopter의 `ApiErrorCarrier`가 요청 단계에서는 `INTERNAL_ERROR`로 나간다. | 완료 | Wave 1–2 P8 (fcddab7e·Wave 2 커밋): S5-#6a와 같은 결함, 같은 수정·같은 테스트. 수정 방향 중 category switch 3개(`GraphQlWireErrorMapper.category`·`clientMessage`, `GraphQlWireErrors.classificationOf`)를 EnumMap 표 하나로 합치는 일은 지시대로 하지 않음 — Wave 3 3-A(Category별 한국어 문구 표를 shared-contract에)에서 `clientMessage`가 그 표로 대체되므로 그때 함께. 커밋 `aa5f4d90` | - | `GraphQlWireErrorMapper`에 `map(Throwable, GraphQlErrorContext)` 진입점 하나를 둔다. platform rejection을 먼저 보고, 그다음 application mapping(`ApiErrorCarrier`), 마지막에 internal로 처리한다. interceptor·instrumentation·field resolver 세 곳이 모두 이 mapper bean을 받는다(`GraphQlPlatformAutoConfiguration.java:388-396`에서 주입). category switch 3개(`GraphQlWireErrorMapper.java:94`, `GraphQlWireErrors.java:56`, `clientMessage`)는 `EnumMap` 표 하나로 합친다. |
| NEW-9b | Nit | `shared-contract`의 `OperationalRecordStorePort` 패키지는 사용처가 0이다. | 남음 | `src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/`(3개 파일). 이 패키지 밖에서 `shared.opstore`를 참조하는 곳은 main·test 모두 0건이다. 유일한 소비자였던 graphql `advanced/**`는 삭제됐다(`docs/capability-status.md:211`). | W3 | `shared/opstore/` 3개 파일을 삭제한다. `src/shared-contract/CLAUDE.md` 책임 목록에 있으면 그 줄도 지운다. `docs/study/graphql-walkthrough.ko.md:125,2064,2133`의 언급은 NEW-14에서 함께 고친다. |
| NEW-9b | Nit | `shared-contract`의 `OperationalRecordStorePort` 패키지는 사용처가 0이다. | 해당 없음(코드 삭제) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `d54909c4`(opstore 삭제). `docs/study/graphql-walkthrough.ko.md` 언급은 NEW-14에서 | - | `shared/opstore/` 3개 파일을 삭제한다. `src/shared-contract/CLAUDE.md` 책임 목록에 있으면 그 줄도 지운다. `docs/study/graphql-walkthrough.ko.md:125,2064,2133`의 언급은 NEW-14에서 함께 고친다. |
| NEW-10a | Consider | web 운영 경로에 JSON 중복 키 거부가 없다. | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): `RequestBodyBoundaryTest.duplicateJsonKeyIsRejectedAsValidationFailure`(`{"role":"user","role":"admin"}` → 400 `VALIDATION_FAILED`) FAIL(`Status expected:<400> but was:<200>`)→PASS. `JsonMapperBuilderCustomizer`로 `StreamReadFeature.STRICT_DUPLICATE_DETECTION`(`src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMvcPlatformAutoConfiguration.java:84`). 위치는 현황표의 `WebAdapterAutoConfiguration` 대신 같은 leaf의 `WebMvcPlatformAutoConfiguration`(요청 경계 필터와 같이 servlet 앱 조건·`backend.web.mvc.enabled`에 묶이고, 테스트가 무거운 security 조립 없이 이 루트 하나로 검증됨) | - | `adapter:inbound:web`에 `JsonMapperBuilderCustomizer` 빈 하나를 두고 `StreamReadFeature.STRICT_DUPLICATE_DETECTION`을 켠다(Jackson 3, `tools.jackson.core`). 위치는 `WebAdapterAutoConfiguration` import 목록이다. contract test는 `{"a":1,"a":2}` → 400을 단언한다. |
| NEW-10b | Consider | CORS origin의 형식을 기동 때 검증하지 않는다(scheme/host/port 형태, path·trailing slash·`null` origin). | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): `CorsSettings` compact constructor가 origin마다 `URI` 파싱: `http`/`https`, host 필수, path(끝 `/` 포함)·query·fragment·user info·와일드카드 호스트·`"null"` 거부, `*`는 기존대로 credentials 없을 때만. 메시지에 `APP_SECURITY_CORS_ORIGINS (ca-skeleton.cors.allowed-origins)`. 테스트는 I-8b 행 | - | `CorsSettings` compact constructor에 origin마다 `URI` 파싱을 추가한다. `http`·`https` scheme과 host가 있어야 하고, path·query·fragment·trailing `/`와 `"null"`은 금지한다. `*`는 credentials가 없을 때만 허용한다. 실패하면 env 키 이름을 담은 메시지로 기동을 실패시킨다(기존 메시지 형식을 따른다). |
| NEW-10c | Required | 신뢰하지 않는 forwarded 헤더를 거부하는 장치가 없다. rate-limit의 `FORWARDED_HEADERS_TRUSTED`는 XFF의 맨 왼쪽 값(클라이언트가 조작 가능)을 쓴다. | 완료 | Wave 1–2 P10 (fcddab7e·Wave 2 커밋): I-5a와 같은 수정(같은 커밋·테스트). 현황표 수정 방향(`trusted-proxies` CIDR 설정 추가)은 오케스트레이터 결정(모드 삭제 + native/internal-proxies)으로 대체. `.env.example`이 `framework`(모든 peer의 XFF를 믿음)를 기본으로 권하던 것도 이 행의 원인이라 `native`로 바꾸고 `framework`는 rate limit 기동 거부로 막음 | - | `EdgeRateLimitTransportSettings`에 `trusted-proxies`(CIDR 목록)를 추가한다. resolver는 remoteAddr가 trusted일 때만 XFF를 오른쪽에서부터 읽어 첫 번째 untrusted 주소를 쓰고, 아니면 remoteAddr를 쓴다. `FORWARDED_HEADERS_TRUSTED`인데 `trusted-proxies`가 비어 있으면 기동을 거부한다. `server.yml` 주석에는 `native` + `server.tomcat.remoteip.internal-proxies`를 명시하라고 적는다. |
| NEW-10d | Nit | web fixture 앱 2개와 sample이 `WebAdapterAutoConfiguration` 전체를 제외한다. sample webSystemTest 4곳은 문자열 이름으로 제외한다. | 남음 | 클래스로 제외: `src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java:38`, `PipelineOrderFixtureApplication.java:46`, `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java:30,49`. 문자열로 제외: `OpenApiDriftContractTest.java:172`, `OpenApiSnapshotTest.java:103`, `DateHeaderContractTest.java:69`, `VirtualThreadMdcE2ETest.java:152`(모두 `src/sample-portfolio/src/webSystemTest/...`). 제외하는 이유는 production security chain을 빼기 위해서다(`ContractFixtureApplication.java:27-30`). | W3 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java`의 `@Import` 목록을 `WebAdapterAutoConfiguration`(core)과 `WebSecurityAutoConfiguration`(`JwtDecoderConfig`·`SecurityConfig`·`MethodSecurityConfig`·`RedisSessionWebConfig`·`JwtToAuthenticatedPrincipalConverter`·`AuthorizationAdapter`)으로 나눈다. fixture·sample은 security root만 클래스로 제외하고, sample은 `dev.caskeleton.adapter.inbound.web` component scan(`SamplePortfolioApplication.java:31-40`)을 지운다. 문자열 제외는 클래스 참조로 바꾼다. |
| NEW-10d | Nit | web fixture 앱 2개와 sample이 `WebAdapterAutoConfiguration` 전체를 제외한다. sample webSystemTest 4곳은 문자열 이름으로 제외한다. | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `WebAdapterAutoConfiguration`(envelope·filter·health·rate limit)과 새 `WebSecurityAutoConfiguration`(JwtDecoderConfig·SecurityConfig·MethodSecurityConfig·RedisSessionWebConfig·JwtToAuthenticatedPrincipalConverter·AuthorizationAdapter·RolePermissionRegistry + 보안 settings)으로 분리, 둘 다 imports 등록(`WebAutoConfigurationRegistrationTest` 목록 추가). sample webSystemTest 4곳·sample slice 테스트의 문자열 `excludeName`을 클래스 참조로. fixture 앱 2개(`ContractFixtureApplication`·`PipelineOrderFixtureApplication`)는 core root가 RequestLoggingFilter(pseudonymizer 필요)를 가져오므로 두 root를 클래스로 제외(수정 방향의 "security root만"은 fixture엔 맞지 않음 — 이유 주석). app-bootstrap slice/IT 6곳에 security root 제외·import 추가 | - | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java`의 `@Import` 목록을 `WebAdapterAutoConfiguration`(core)과 `WebSecurityAutoConfiguration`(`JwtDecoderConfig`·`SecurityConfig`·`MethodSecurityConfig`·`RedisSessionWebConfig`·`JwtToAuthenticatedPrincipalConverter`·`AuthorizationAdapter`)으로 나눈다. fixture·sample은 security root만 클래스로 제외하고, sample은 `dev.caskeleton.adapter.inbound.web` component scan(`SamplePortfolioApplication.java:31-40`)을 지운다. 문자열 제외는 클래스 참조로 바꾼다. |
| NEW-11 | Consider | fileserver를 JPA 줄 없이 고르면 Boot 관계형 자동 설정이 켜지고, 원인을 알기 어려운 오류로 기동에 실패한다. | 완료 | Wave 1–2 P4 (fcddab7e·Wave 2 커밋): `src/composition/fileserver-platform/build.gradle`에 `runtimeOnly project(':adapter:outbound:persistence-jpa')`, `src/config/architecture/modules.json` edge 추가, README 갱신(`src/composition/fileserver-platform/README.md` 저장소 줄, `src/README.md:270` 표). `architectureCheck`·`verifyDependencyLocks` 통과. JPA 줄 없이 fileserver만 고른 조립의 기동 테스트는 추가하지 않았다: 모든 테스트 classpath(app-bootstrap integrationTest 포함)에 persistence-jpa가 이미 있어 "없는 조립"을 만들 수 없다. 대신 조립 lane `:app-bootstrap:integrationTest`(fileserver PG 왕복 포함 4건) 통과 | - | 결정(2026-09-25): 한 줄 원칙 — fileserver·notification composition이 persistence-jpa를 `runtimeOnly`로 함께 가져옴 |
| NEW-12 | Nit | `bootstrap.autoconfigure` 패키지가 component scan 범위 안에 있다. | 남음 | `src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/CaSkeletonApplication.java:19`: `@SpringBootApplication`이 `dev.caskeleton.bootstrap..` 전체를 scan한다. 지금 `autoconfigure/` 아래 4개 root는 imports에 있어서 Boot의 `AutoConfigurationExcludeFilter`가 걸러낸다. 그 외 stereotype은 `@ConfigurationProperties` record 3개뿐이다(grep: `@Configuration`·`@Component` 0건). 지금 당장 문제는 없고, 나중에 root가 아닌 `@Configuration`을 추가하면 조건 없이 등록되는 잠재 위험이다. | W3 | NEW-2 이동 뒤에 남는 `common`·`tracing` root를 scan 밖 패키지(예: `dev.caskeleton.autoconfigure.bootstrap`)로 옮긴다. 옮기지 않을 거면 architectureTest에 "`bootstrap.autoconfigure..`의 `@Configuration`은 `@AutoConfiguration`이어야 한다" 규칙을 추가한다. |
| NEW-12 | Nit | `bootstrap.autoconfigure` 패키지가 component scan 범위 안에 있다. | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): 이동 대신 ArchUnit 규칙 `BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS`(`CompositionRootBoundaryArchitectureTest.java:75`): `bootstrap.autoconfigure..`에서 `@Component` 메타 annotated 클래스는 `@AutoConfiguration`이어야 함(현재 5 root로 비어있지 않음). `ArchRuleDiscoveryContractTest` 목록 추가. P18이 outbox·idempotency root를 옮기는 중이라 패키지 이동은 피함 | - | NEW-2 이동 뒤에 남는 `common`·`tracing` root를 scan 밖 패키지(예: `dev.caskeleton.autoconfigure.bootstrap`)로 옮긴다. 옮기지 않을 거면 architectureTest에 "`bootstrap.autoconfigure..`의 `@Configuration`은 `@AutoConfiguration`이어야 한다" 규칙을 추가한다. |
| NEW-13a | Consider | `verifyEnvKeys`는 bootstrap에 유지하기로 결정됐는데, 문서는 아직 "옮기지 않은 검사"라고 적고 있다. | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): `CLAUDE.md`·`AGENTS.md`·`src/README.md`·build-logic README를 "verifyEnvKeys = app-bootstrap 유지(결정 4), 구현은 build-logic `ca.config-contract`, build-tools 삭제"로 수정 | - | JPA evidence를 삭제하면(NEW-13b) build-tools에는 `ca.config-contract` 하나만 남는다. 그 plugin을 `src/build-logic/`으로 옮기고 `src/settings.gradle:6` `includeBuild('build-tools')`와 `build-logic.yml`의 build-tools 단계를 지운다. `CLAUDE.md:32`·`AGENTS.md:68`은 "verifyEnvKeys = app-bootstrap 유지"로 고친다. |
| NEW-13b | Consider | JPA evidence manifest(`ca.jpa-evidence`, `ca.jpa-qualification`)를 폐기하고 leaf 테스트로 옮기기로 결정됐다. 아직 코드에 남아 있다. | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): O3-2와 같음. 수정 방향과 다른 점: `readiness-cards.yaml`·`release-registry.json`은 지우지 않음 — 결정 4·X1 결정은 "leaf 테스트로 옮김"이고, `release-registry.json`은 persistence-jpa testFixtures `JpaReleaseManifest`·`JpaReleaseRenderingTest`·`jpaReleaseQualification`의 SSOT, 카드 파일은 `JpaReadinessRegistryTest`와 readiness 레인 `requires`의 입력. `MessagingCapabilityRegistryContractTest`는 JPA 카드를 읽지 않음(`config/messaging`만 읽음, 현황표 근거가 틀림) | - | build-tools의 `jpa/` 패키지와 두 plugin id를 삭제한다. evidence가 확인하던 사실(마이그레이션 순서, PG 버전 매트릭스, lane 존재)은 persistence-jpa `postgresqlIntegrationTest`의 JUnit 테스트로 옮긴다. yaml·json 입력과 `jpa-r2-evidence.yml`, integration-main의 `jpa-candidate-evidence` 잡, jpa-release의 두 태스크를 지운다. `MessagingCapabilityRegistryContractTest`에서 readiness-cards 의존을 뺀다. |
| NEW-13c | Nit | redis topology lane은 유지하기로 결정됐다. | 완료 | lane plugin은 build-logic `ca.redis-topology-lane`에 있고, `src/adapter/outbound/cache-redis/build.gradle:4,51-53`, `src/adapter/outbound/redis-sdk/build.gradle:3,19-21`, `src/adapter/outbound/redis-runtime/build.gradle:5`이 쓴다. CI는 `redis-sdk-topology.yml`이다. 코드는 옮길 필요가 없다. | W5 | 문서에 "유지"라고만 적는다(`docs/superpowers/plans/2026-09-25-capability-module-packaging.md` 진행 기록 Wave 5 "남은 설계 결정" 문장). |
@@ -1173,7 +1174,7 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검
| NEW-16 | 발견 | `integrationCheck`가 로컬에서 통과할 수 없는 lane을 묶음 — Redis topology 3개는 `-Predis.topology.mode` 없이 fail-closed, AWS 보호 lane은 보호 자격 증명 env가 없으면 실패. 그래서 집계 태스크가 항상 실패 | 완료 | Wave 3 W3-P16 (Wave 3 라운드 1 커밋): `strictTestLanes`에 `explicitOnly(reason)`(모든 집계에서 빠지고 집계가 돌 때 이유 출력) — `StrictTestLaneConventionTest.anExplicitOnlyLaneStaysOutOfEveryAggregate` FAIL→PASS. Redis topology는 `-Predis.topology.mode`가 없으면 explicit-only(`RedisTopologyLanePluginFunctionalTest.withoutADeclaredModeTheLaneStaysOutOfTheIntegrationAggregate`·`aDeclaredModePutsTheLaneInTheIntegrationAggregate` FAIL→PASS), AWS lane은 `OBJECT_STORAGE_AWS_QUALIFICATION_ENABLED=true`가 없으면 explicit-only, httpclient `disabledProxyFailsBeforeARequestCanBeSent`는 Docker userland proxy와 무관한 loopback 닫힌 포트 시나리오 `refusedConnectionFailsBeforeARequestCanBeSent`로 교체(P11-new-3도 해소). `./gradlew integrationCheck --continue` BUILD SUCCESSFUL(14m), 기존 실패 3종 없음, 빠진 lane 4개는 이유 출력 | - | 매개변수·자격 증명이 필요한 lane은 `integrationCheck`에서 빼고 전용 워크플로에서만(또는 입력이 있을 때만 포함) |
| P14-new-1 | 발견 | operator force-delete(`application-fileserver/.../admin/DefaultFileserverAdminService.java:167`)가 P4-new-4와 같은 결함 — 진행 중 upload를 지우면 세션이 ACTIVE로 남고 staging 정리가 예약되지 않는다. | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `23cababd` (W2). `FileserverAdminServiceTest.forceDeletingAnInProgressUploadEndsItsSessionAndSchedulesItsStagingForCleanup` FAIL(`Expecting actual: [false, []] to contain exactly (and in same order): [true, [CleanupRequest[type=CANCELLED_STAGING, …]]]`)→PASS. lifecycle delete의 규칙을 `FileRetirement.retireWithUnfinishedUpload`(`cleanup/FileRetirement.java:57`)로 옮겨 `DefaultFileserverAdminService.forceDelete`(`admin/DefaultFileserverAdminService.java:173`)와 공유, 관리 서비스 생성자에 `StagingUploadLocatorPort` | - | lifecycle delete와 같은 `unfinishedUpload` 처리를 admin 경로에도(생성자에 `StagingUploadLocator`). 라운드 2 P24 |
| P14-new-2 | 발견 | `S3AsyncResponseBodyBridgeTest.deliversAnExactBoundedBodyOnTheWorkerAndInvalidatesTheSource`가 전체 `check` 부하에서 간헐 실패(`Expecting code to raise a throwable`), 단독 통과. | 완료 | Wave 3 P24 (라운드 2 커밋): P24-new-1 — bridge 순서 경합(결과 게시 전 source 무효화, 취소 전 원인 기록) 수정, bridge 테스트 40회 반복 통과 | - | 타이밍 의존 제거(결정적 executor/latch) |
| P14-new-3 | 발견 | main에 `ReconcilePosterImageUploadUseCase`를 부르는 worker가 없다(`claimPending` 호출자 0). 게시가 이긴 ABORT_AUTHORIZED intent는 reconcile 명령이 와야 붙는다. | 남음 | Wave 2.5 P14 결과 파일 | W3 | sample에 reconcile worker(PENDING·ABORT_AUTHORIZED 모두)를 두거나 수동 명령임을 문서화. 라운드 2 P25 |
| P14-new-3 | 발견 | main에 `ReconcilePosterImageUploadUseCase`를 부르는 worker가 없다(`claimPending` 호출자 0). 게시가 이긴 ABORT_AUTHORIZED intent는 reconcile 명령이 와야 붙는다. | 완료(수동 명령 경로 선택) | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): worker를 두지 않고 `ReconcilePosterImageUploadUseCase`가 명시적 명령임을 javadoc에 명시(sample에 trigger 없음, 만들면 PENDING·ABORT_AUTHORIZED 둘 다 골라야 함, `claimPending`은 PENDING만이라 그 선택자가 아님 — 포트 javadoc). `PosterImageAbortReconcileRaceTest.theReconcileCommandFinishesAPendingOrAbortAuthorizedIntent`(두 상태 → READY + attach) PASS. 근거: worker는 새 claim 포트·JPA 쿼리·settings·job·env 키·vendor 테스트가 필요하고, `claimPending`이 handoff claimant를 바꿔 reconcile의 claimant(`poster-image-<opId>`)와 충돌할 수 있어 설계 결정이 더 필요하다. 명령 경로 고정이 더 작다 | - | sample에 reconcile worker(PENDING·ABORT_AUTHORIZED 모두)를 두거나 수동 명령임을 문서화. 라운드 2 P25 |
| P14-new-4 | 발견 | P2-new-3 수정 뒤 기본 요구 집합(`CONDITIONAL_RETIREMENT` 포함, `ObjectStorageDestinationSettings.java:40`)을 쓰는 S3 destination은 기동 시 거부된다 — 운영 provider인 S3로 sample 포스터 게시(`PublishPosterImageUseCase.java:197`)를 쓸 수 없다. | 완료 | Wave 3 W3-P24 (Wave 3 라운드 2 커밋): `6c989330`. MinIO lane으로 확인한 벤더 사실: DELETE의 `If-Match`는 무시된다(stale ETag로도 삭제 — `MinioManagedObjectContractTest.aStaleEtagConditionOnDeleteIsIgnored`), SDK 2.30 문서도 directory bucket 전용. 반면 version-id DELETE는 HEAD 뒤 덮어쓴 version을 남긴다(`aVersionIdDeleteRemovesOnlyTheVerifiedVersionEvenAfterAnOverwrite`), 버전 관리 없는 bucket의 HEAD는 version id가 없다(`anUnversionedBucketGivesHeadNoVersionId`), `GetBucketVersioning`은 켠 곳만 Enabled(`bucketVersioningIsReportedEnabledOnlyWhereItWasTurnedOn`). 그래서 `S3ManagedObjectProvider.retire`(`s3/S3ManagedObjectProvider.java:133`)는 HEAD 검증 뒤 versionId DELETE, version id가 없으면 by-key 삭제 대신 UNSUPPORTED. `S3ManagedObjectProviderTest.retirementDeletesExactlyTheProviderVersionItVerified`·`retiringAnAbsentObjectReportsNothingRetired`·`retirementInABucketWithoutVersioningIsRefusedWithoutDeleting` FAIL(`version-aware S3 retirement is not available in the managed-single profile`)→PASS. binding의 CONDITIONAL_RETIREMENT 거부 제거(`S3ProviderBindingTest.aProfileMayClaimConditionalRetirement`), retire를 주장하는 profile은 기동 때 `GetBucketVersioning`이 Enabled여야 한다(`s3/S3ObjectStorageProviderContribution.java:128`, `S3ProviderCompositionTest.aDestinationWithTheDefaultRequirementsStartsOverAVersionedBucket`·`aRetirementClaimOverABucketWithoutVersioningFailsStartupAndClosesItsClient`). 남은 사실(이 행 밖): S3 provider type은 여전히 `ObjectStorageDeploymentReadiness`(filesystem-local-dev만)에 없어 기본 runtime compiler가 readiness로 거부한다 — AWS qualification lane으로 readiness를 올리는 일은 별개 | - | S3 조건부 retire 구현(버전·ETag 조건 삭제, MinIO lane으로 검증) 또는 기본 요구 집합 재검토. 라운드 2 P24 |
| P14-new-5 | 발견 | 테스트 규칙 잔여: `PosterImagePublicationWorkflowTest`가 testFixtures `InMemoryPosterImageUploadIntentStore` 대신 자기 `FakeIntents` 사용, `application-objectstorage`에 testFixtures가 없어 포트 대역이 테스트 안 스텁. | 남음 | Wave 2.5 P14 결과 파일 | W4 | 공용 fake로 교체, application-objectstorage testFixtures 신설 |
| P17-new-1 | 발견 | `GrpcMethodPolicy` 기본 method 한도 4 MiB가 기본 server profile 1 MiB와 어긋남. | 완료 | Wave 3 P17: N-10a validator가 드러냄(`aCoherentConfigurationStarts` FAIL), 기본값을 `GrpcTransportLimits.DEFAULT_MAX_MESSAGE_BYTES`로 | - | - |
@@ -1197,3 +1198,6 @@ Wave 1–2 구현 묶음(`P1`–`P13`)이 작업 중 찾은 결함과 통합 검
| P24-new-1 | 발견 | S3 응답 bridge가 source 무효화 전에 결과를 게시하고, 실패 원인 기록 전에 취소해 테스트가 간헐 실패(P14-new-2·P16-new-4의 원인). | 완료 | Wave 3 P24: 순서 수정, bridge 테스트 40회 반복 통과 | - | - |
| P24-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0. | 남음 | Wave 3 P24 결과 파일 | W3 | P18 통합 뒤 삭제(같은 파일) |
| P24-new-3 | 발견 | `FileVerifier`가 application-fileserver에 있지만 fileserver adapter만 쓴다. | 남음 | Wave 3 P24 결과 파일 | W3 | adapter로 이동 |
| P25-new-1 | 발견 | `TomcatWebSocketAbuseIT` shutdown 테스트가 부하 중 `20.0006s < 20s`로 한 번 실패, 재실행 4회 통과(타이밍 의존). | 남음 | Wave 3 P25 결과 파일 | W4 | 시간 경계 단언을 결정적 신호로 |
| P25-new-2 | 발견 | legacy upload 삭제 뒤 `PosterEventPublisher.publishImageAttached`·`PosterImageAttached` 호출자 0(= P24-new-2). | 남음 | Wave 3 P25 결과 파일 | W3 | P24-new-2와 함께(P28) |
| P25-new-3 | 발견 | sample `local` 프로필이 기본값과 같은 `object-storage.enabled=false`만 남김. | 남음 | Wave 3 P25 결과 파일 | W5 | 불필요한 설정 삭제 또는 이유 주석 |
@@ -228,7 +228,7 @@ W1·W2 잔여 21행(Wave 2.5)은 P14로 1라운드에서 함께 처리한다. W1
| P22 | 3 | Redis 구조 · startup rule | `G-4i` `G-6b` `G-7a` `G-7c` `G-7d` `G-7e` `G-8` `X1-지도-lock / lease / fencing` `S1-#15c` `S3-#3a` `S3-#3b` `S3-#4b` `S3-#5` `S3-#9` `S6-#2c` `S6-#3a` |
| P23 | 3 | notification: SES → sesv2(결정 17), `persistence-notification` 추출, SRP | `S1-#4` `S1-#9` `S1-#10b` `S2-#1b` `S2-#6c` `S2-#8a` `S2-#13b` `S4-#3c` `S4-#4b` `S4-#9` `S4-#14b` `S4-#15` `S4-lead-3` `S4-lead-5` |
| P27 | 3 | 빌드 잔여(결정 28·29·31): O3-5 나머지(`ca.release-provenance`·auxiliary → `jvm-test-suite`), messaging 카드 검증 leaf 테스트로, cosign 서명, `INTERNAL_ERROR` retryable=false, persistence-fileserver `ca.api-surface` | `BUILD-결론-1` `BUILD-O3-5` `X1-#7a` `X1-지도-readiness…` `BUILD-계획-C` `P15-new-3` `P16-new-6` |
| P28 | 3 | 로컬 보안 파일시스템 primitive 공용화(보안 민감 재작성, P24에서 분리) + fileserver 잔여 | `S4-lead-2` `P24-new-2` `P24-new-3` |
| P28 | 3 | 로컬 보안 파일시스템 primitive 공용화(보안 민감 재작성, P24에서 분리) + fileserver 잔여 | `S4-lead-2` `P24-new-2` `P25-new-2` `P24-new-3` `S6-#10a` `S1-#6b` `S1-#18b`(결정 32) |
| P20 | 4 | 3-B 설정 prefix `app.*`(결정 16), strict 바인딩 | `X2-P1-3c` `S3-lead-2` `S3-lead-4` `S6-#14` `P11-new-1` |
- [x] 라운드 1: P14 · P15 · P16 · P17 → 통합·검증·커밋 (2026-09-28, `9fdb0af4`·`c4a066df`·라운드 1 마무리 커밋)
+1 -2
View File
@@ -297,6 +297,7 @@ APP_OUTBOX_ENABLED=false
APP_OUTBOX_RELAY_ENABLED=false
APP_OUTBOX_CANONICAL_TRANSPORT_ENABLED=false
APP_NOTIFICATION_PLATFORM_ENABLED=true
APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE=ko-KR
APP_NOTIFICATION_PLATFORM_MODE=SERVING
# OpenAPI exposure. application-prod.yml pins both false regardless of these.
APP_OPENAPI_DOCS_ENABLED=true
@@ -360,8 +361,6 @@ APP_NOTIFICATION_PLATFORM_MAX_OLDEST_RECONCILIATION_AGE=30m
APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED=false
APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES=65508
APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW=5m
# Empty: forwarded headers are not believed. List load-balancer peers to honour them.
APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES=
# ---- Secrets — supply out of band; never commit a value here ------------------
APP_DATASOURCE_PASSWORD=
+1 -1
View File
@@ -158,7 +158,7 @@ health 스키마만 소유한다.
| depth/complexity 제한 (`cost/`) | `wired` | 같은 테스트의 depth/alias/complexity 케이스 |
| preparsed document cache (`execution/`) | `wired` | `GraphQlPreparsedDocumentAdapter` + 같은 테스트의 캐시 hit 케이스 |
| 커스텀 scalar (`scalar/`) | `wired` | 같은 테스트의 scalar coercion 케이스 |
| 요청 크기 (`http/`, body limit filter) | `wired` | `GraphQlRequestBoundsTest` |
| 요청 크기 (`http/`, body limit filter) | `wired` | `runtime/GraphQlPlatformWebInterceptorRequestBoundsTest`(auto-configured interceptor 로 byte·shape·extension 거부), `http/GraphQlRequestBoundsTest` |
| 관측 tag cardinality (`observation/`) | `wired` | `runtime/GraphQlRequestObservationConventionAdapter` 가 Spring 의 `ExecutionRequestObservationConvention` 을 구현해 Boot 의 `GraphQlObservationAutoConfiguration` 이 이 컨벤션을 가져간다. `autoconfigure/GraphQlObservationWiringTest`(프레임워크가 실제로 해석), `runtime/GraphQlRequestObservationConventionAdapterTest`(실제 `MeterRegistry` 에 임의 이름 10,000개 → series 1개) |
| object 인가 (`security/`) | `modelled` | 답하는 계약은 중립 `dev.caskeleton.application.security.ObjectAccessPolicy` 가 소유하고 이 leaf 는 `ApplicationObjectAuthorization` 매핑만 가진다. 실행 경로에 연결하는 configuration 은 없다 |
| DataLoader/batching (`dataloader/`) | `wired` | `runtime/GraphQlBatchLoaderRegistrationTest` (실제 graphql-java 실행 + Spring `BatchLoaderRegistry`, 50 parent → 3 downstream 호출), `dataloader/GraphQlBatchContractTest` |
@@ -0,0 +1,65 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry;
import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar;
import java.time.Clock;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** Batch policy, per-loader factory and the registrar that puts them on the DataLoader path. */
@Configuration(proxyBeanMethods = false)
class GraphQlDataLoaderConfiguration {
/**
* The batch policies an adopter registers, empty until one does.
*
* <p>A bean rather than something each adopter constructs, because the two things downstream of
* it — the loader factory and the registrar — were beans nowhere, and a platform whose N+1
* protection has to be assembled by hand is a platform whose N+1 protection is not applied.
*
* @return the registry
*/
@Bean
@ConditionalOnMissingBean
GraphQlBatchPolicyRegistry graphQlBatchPolicyRegistry() {
return new GraphQlBatchPolicyRegistry();
}
/**
* Supplies the per-loader batch policy and executor.
*
* @param policies the registered policies
* @param properties the platform settings, which supply the batch ceiling
* @param graphQlPlatformClock the clock deadlines are measured against
* @return the factory
*/
@Bean
@ConditionalOnMissingBean
GraphQlDataLoaderFactory graphQlDataLoaderFactory(
GraphQlBatchPolicyRegistry policies,
GraphQlPlatformSettings properties,
Clock graphQlPlatformClock) {
// The page ceiling is the batch ceiling. Both answer the same question — how many rows one
// downstream call may ask for — and a batch limit larger than the page limit would let a single
// request fan out past the bound the same request already accepted for its page.
return new GraphQlDataLoaderFactory(
policies, properties.limits().maximumPageSize(), graphQlPlatformClock);
}
/**
* Wraps an adopter's batch loader in the platform's chunking, budget and request scope.
*
* <p>An adopter still supplies the downstream call, because only the adopter has one. What it no
* longer supplies is the machinery around it.
*
* @param factory the loader factory
* @return the registrar
*/
@Bean
@ConditionalOnMissingBean
GraphQlBatchLoaderRegistrar graphQlBatchLoaderRegistrar(GraphQlDataLoaderFactory factory) {
return new GraphQlBatchLoaderRegistrar(factory);
}
}
@@ -0,0 +1,40 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlExceptionResolver;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataFetcherExceptionResolver;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.execution.DataFetcherExceptionResolver;
/** The one error vocabulary the transport, the pre-execution chain and the resolvers share. */
@Configuration(proxyBeanMethods = false)
class GraphQlErrorConfiguration {
/**
* The application's deliberate failure mappings.
*
* <p>Empty by default, which means every unrecognised failure is masked. An adopter replaces this
* bean to give its own modelled failures a stable code rather than an opaque internal error.
*/
@Bean
@ConditionalOnMissingBean
GraphQlExceptionResolver graphQlApplicationExceptionMappings() {
return GraphQlExceptionResolver.defaults();
}
/** The single vocabulary every client-visible error is produced from. */
@Bean
@ConditionalOnMissingBean
GraphQlWireErrorMapper graphQlWireErrorMapper(GraphQlExceptionResolver mappings) {
return new GraphQlWireErrorMapper(mappings);
}
/** Adapts the mapper onto Spring's data-fetcher exception contract. */
@Bean
@ConditionalOnMissingBean(GraphQlDataFetcherExceptionResolver.class)
DataFetcherExceptionResolver graphQlDataFetcherExceptionResolver(GraphQlWireErrorMapper mapper) {
return new GraphQlDataFetcherExceptionResolver(mapper);
}
}
@@ -0,0 +1,133 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlComplexityCalculator;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentShapeAnalyzer;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitPolicy;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimits;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipeline;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlOperationSelectionHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy;
import graphql.execution.instrumentation.Instrumentation;
import java.time.Clock;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* The pre-execution chain — select the operation, authorize it, judge its cost — and the
* instrumentation that puts it on the real execution path.
*/
@Configuration(proxyBeanMethods = false)
class GraphQlExecutionChainConfiguration {
/**
* Coordinate authorization rules.
*
* <p>There is no safe default here, so production does not get one. Coordinate rules are
* application knowledge: a deny-by-default skeleton policy would answer nothing and adopters
* would replace it with an allow-all one, while an allow-by-default policy shipped into
* production would be an unauthorized endpoint. So a development mode gets the permissive default
* that lets the schema be explored, and a production {@code backend.graphql.deployment-mode}
* refuses to start without an explicit policy.
*/
@Bean
@ConditionalOnMissingBean
GraphQlAuthorizationPolicy graphQlAuthorizationPolicy(GraphQlPlatformSettings properties) {
if (properties.deploymentMode() == null) {
throw new GraphQlPlatformConfigurationException(
List.of(GraphQlDeploymentMode.REQUIRED_MESSAGE));
}
if (properties.production()) {
throw new GraphQlPlatformConfigurationException(
List.of(
"backend.graphql.deployment-mode="
+ properties.deploymentMode()
+ " requires an explicit GraphQlAuthorizationPolicy bean; the platform has no "
+ "application coordinates to authorize on its own"));
}
return GraphQlAuthorizationPolicy.builder().denyByDefault(false).build();
}
/** Registered field costs; unregistered coordinates fall back to a conservative weight. */
@Bean
@ConditionalOnMissingBean
GraphQlCostCatalog graphQlCostCatalog() {
return GraphQlCostCatalog.of();
}
/** Document structure measurement. */
@Bean
@ConditionalOnMissingBean
GraphQlDocumentShapeAnalyzer graphQlDocumentShapeAnalyzer() {
return new GraphQlDocumentShapeAnalyzer();
}
/** Per-field pricing, driven by the page policy the client policy declares. */
@Bean
@ConditionalOnMissingBean
GraphQlComplexityCalculator graphQlComplexityCalculator(
GraphQlCostCatalog catalog, GraphQlClientPolicy clientPolicy) {
return new GraphQlComplexityCalculator(
catalog, clientPolicy.defaultPageSize(), clientPolicy.maxPageSize());
}
/** Structural ceilings derived from the client policy. */
@Bean
@ConditionalOnMissingBean
GraphQlStructuralLimitPolicy graphQlStructuralLimitPolicy(GraphQlClientPolicy clientPolicy) {
return new GraphQlStructuralLimitPolicy(GraphQlStructuralLimits.from(clientPolicy));
}
/** The executable chain: select the operation, authorize it, judge its cost. */
@Bean
@ConditionalOnMissingBean
GraphQlExecutionChain graphQlExecutionChain(
GraphQlClientPolicy clientPolicy,
GraphQlAuthorizationPolicy authorizationPolicy,
GraphQlDocumentShapeAnalyzer analyzer,
GraphQlStructuralLimitPolicy structuralLimits,
GraphQlComplexityCalculator calculator,
Clock graphQlPlatformClock) {
return GraphQlExecutionChain.stable(
new GraphQlOperationSelectionHandler(clientPolicy),
new GraphQlDocumentAuthorizationHandler(
new GraphQlAuthorizationInterceptor(authorizationPolicy), analyzer, clientPolicy),
new GraphQlCostBudgetHandler(
analyzer, structuralLimits, calculator, clientPolicy, graphQlPlatformClock));
}
/**
* The execution pipeline, derived from the handlers that actually run.
*
* <p>Derived rather than declared: a hand-written stage list can describe a pipeline the code
* does not have, and this one cannot. The startup check validates this value, so a chain
* assembled in the wrong order fails the refresh instead of serving requests.
*/
@Bean
@ConditionalOnMissingBean
GraphQlExecutionPipeline graphQlExecutionPipeline(GraphQlExecutionChain chain) {
return chain.pipeline();
}
/**
* Puts the chain on the real execution path.
*
* <p>Spring for GraphQL picks up every {@code Instrumentation} bean, so this is what turns the
* policy objects from a catalogue into something a request has to pass.
*/
@Bean
@ConditionalOnMissingBean(GraphQlPlatformInstrumentation.class)
Instrumentation graphQlPlatformInstrumentation(
GraphQlExecutionChain chain, GraphQlWireErrorMapper errors) {
return new GraphQlPlatformInstrumentation(chain, errors);
}
}
@@ -0,0 +1,87 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlMetricCardinalityPolicy;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlOperationNameCardinality;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlRequestObservationConvention;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlSensitiveAttributeFilter;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.observation.ExecutionRequestObservationConvention;
/** Bounded-cardinality observation conventions for requests, resolvers and DataLoaders. */
@Configuration(proxyBeanMethods = false)
class GraphQlObservationConfiguration {
/** The metric attribute allowlist. */
@Bean
@ConditionalOnMissingBean
GraphQlMetricCardinalityPolicy graphQlMetricCardinalityPolicy() {
return GraphQlMetricCardinalityPolicy.standard();
}
/** The sensitive-attribute filter. */
@Bean
@ConditionalOnMissingBean
GraphQlSensitiveAttributeFilter graphQlSensitiveAttributeFilter(
GraphQlMetricCardinalityPolicy policy) {
return new GraphQlSensitiveAttributeFilter(policy);
}
/**
* Which operation names may become metric labels.
*
* <p>Defaults to the deployment's declared list, which is empty unless configured. Empty means
* every named operation collapses to one label: correct by default, and legible for any adopter
* who names the operations they care about.
*/
@Bean
@ConditionalOnMissingBean
GraphQlOperationNameCardinality graphQlOperationNameCardinality(
GraphQlPlatformSettings properties) {
return new GraphQlOperationNameCardinality(properties.observedOperationNames());
}
/** The request observation convention. */
@Bean
@ConditionalOnMissingBean
GraphQlRequestObservationConvention graphQlRequestObservationConvention(
GraphQlSensitiveAttributeFilter filter, GraphQlOperationNameCardinality operationNames) {
return new GraphQlRequestObservationConvention(filter, operationNames);
}
/**
* Hands the bounded request tags to Spring for GraphQL's observation instrumentation.
*
* <p>The convention above is a value; this is the bean Boot's {@code
* GraphQlObservationAutoConfiguration} looks for. Without it the framework falls back to its own
* convention and the platform's cardinality policy applies to nothing that is exported.
*
* @param convention the platform's bounded tag policy
*/
@Bean
@ConditionalOnMissingBean(ExecutionRequestObservationConvention.class)
GraphQlRequestObservationConventionAdapter graphQlExecutionRequestObservationConvention(
GraphQlRequestObservationConvention convention) {
return new GraphQlRequestObservationConventionAdapter(convention);
}
/** The resolver observation convention. */
@Bean
@ConditionalOnMissingBean
GraphQlResolverObservationConvention graphQlResolverObservationConvention(
GraphQlSensitiveAttributeFilter filter) {
return new GraphQlResolverObservationConvention(filter);
}
/** The DataLoader observation convention. */
@Bean
@ConditionalOnMissingBean
GraphQlDataLoaderObservationConvention graphQlDataLoaderObservationConvention(
GraphQlSensitiveAttributeFilter filter) {
return new GraphQlDataLoaderObservationConvention(filter);
}
}
@@ -1,81 +1,33 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile;
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlComplexityCalculator;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlCostCatalog;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlDocumentShapeAnalyzer;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimitPolicy;
import dev.caskeleton.adapter.inbound.graphql.cost.GraphQlStructuralLimits;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlExceptionResolver;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlExecutionPipeline;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheMetrics;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCachePolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlDataLoaderObservationConvention;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlMetricCardinalityPolicy;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlOperationNameCardinality;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlRequestObservationConvention;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlResolverObservationConvention;
import dev.caskeleton.adapter.inbound.graphql.observation.GraphQlSensitiveAttributeFilter;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlCostBudgetHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDataFetcherExceptionResolver;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlDocumentAuthorizationHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlExecutionChain;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlOperationSelectionHandler;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformInstrumentation;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPrincipalResolver;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlRequestObservationConventionAdapter;
import dev.caskeleton.adapter.inbound.graphql.runtime.servlet.GraphQlRequestBodyLimitFilter;
import dev.caskeleton.adapter.inbound.graphql.scalar.GraphQlScalarWiringConfigurer;
import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarDefinition;
import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarManifest;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticationContextFactory;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationInterceptor;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthorizationPolicy;
import graphql.execution.instrumentation.Instrumentation;
import graphql.execution.preparsed.PreparsedDocumentEntry;
import graphql.schema.idl.SchemaPrinter;
import java.time.Clock;
import java.util.List;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.graphql.autoconfigure.GraphQlProperties;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.graphql.execution.DataFetcherExceptionResolver;
import org.springframework.graphql.execution.GraphQlSource;
import org.springframework.graphql.observation.ExecutionRequestObservationConvention;
import org.springframework.graphql.server.WebGraphQlInterceptor;
/**
* Assembles the Stable platform and validates it at startup (Stable plan Task 46).
* Startup validation of the Stable platform (Stable plan Task 46), and the anonymous-caller
* identity every request-context bean shares.
*
* <p>The platform's beans are split by capability — request policy and context, execution chain,
* errors, scalars, observation, preparsed cache, DataLoader, servlet body limit — and each part is
* its own configuration class listed in {@link GraphQlRootAutoConfiguration}'s {@code @Import}.
* This one holds only what runs across all of them: the refresh-time check that the assembled
* platform is safe to serve.
*
* <p>Composes Stable capabilities only. Advanced capabilities are opt-in and must never arrive
* through this configuration — an Advanced capability that activates because the Stable starter is
* on the classpath is exactly the accident the module boundary exists to prevent.
*
* <p>A real {@code @AutoConfiguration}, registered in {@code AutoConfiguration.imports}, and
* ordered after Spring Boot's own GraphQL auto-configuration. Both halves matter: without the
* registration the class was named auto-configuration while behaving as an ordinary
* {@code @Configuration}, so every {@code @ConditionalOnMissingBean} on it was evaluated before an
* adopter's beans existed and silently failed to back off. Without the ordering, this would race
* the framework's own {@code GraphQlSource} and schema beans.
*/
@org.springframework.context.annotation.Configuration(proxyBeanMethods = false)
@Configuration(proxyBeanMethods = false)
public class GraphQlPlatformAutoConfiguration {
/** Client profile applied to a caller with no verified credential. */
@@ -131,507 +83,4 @@ public class GraphQlPlatformAutoConfiguration {
framework == null ? null : framework.getGraphiql().isEnabled()));
};
}
/**
* Caps the raw request body upstream of the JSON decoder, on a servlet stack.
*
* <p>Loaded only where servlets exist. The leaf takes the servlet API as {@code compileOnly}, so
* on a non-web application this class is simply not on the classpath and the condition never
* matches — which is why the guard is {@code @ConditionalOnClass} as well as
* {@code @ConditionalOnWebApplication}.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(jakarta.servlet.Filter.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
static class ServletRequestBodyLimit {
/**
* Registers the cap with the highest precedence.
*
* <p>The whole point is to run before anything reads the body, so it has to precede the
* decoder, Spring Security's filters and any application filter that might buffer the request.
*/
@Bean
@ConditionalOnMissingBean
FilterRegistrationBean<GraphQlRequestBodyLimitFilter> graphQlRequestBodyLimitFilter(
GraphQlClientPolicy clientPolicy, ObjectProvider<GraphQlProperties> frameworkProperties) {
// The body carries the document, the variables and the extensions plus JSON framing, so the
// cap is their sum with room for the envelope rather than any one of them.
long maxBodyBytes =
(long) clientPolicy.maxDocumentBytes()
+ clientPolicy.maxVariablesBytes()
+ clientPolicy.maxVariablesBytes()
+ ENVELOPE_FRAMING_ALLOWANCE_BYTES;
// The endpoint path follows the framework when the framework is there. It is optional
// because the platform can be assembled without Boot's GraphQL auto-configuration — a slice
// test, or a composition root that wires the endpoint itself — and a cap that refuses to
// exist in those contexts would make the leaf harder to test than to secure.
String path = frameworkProperties.getIfAvailable(GraphQlProperties::new).getHttp().getPath();
FilterRegistrationBean<GraphQlRequestBodyLimitFilter> registration =
new FilterRegistrationBean<>(new GraphQlRequestBodyLimitFilter(path, maxBodyBytes));
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
registration.addUrlPatterns(path);
return registration;
}
}
/** Slack for the JSON envelope around the three sized fields. */
static final int ENVELOPE_FRAMING_ALLOWANCE_BYTES = 1024;
/**
* The execution pipeline, derived from the handlers that actually run.
*
* <p>Derived rather than declared: a hand-written stage list can describe a pipeline the code
* does not have, and this one cannot. The startup check above validates this value, so a chain
* assembled in the wrong order fails the refresh instead of serving requests.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlExecutionPipeline graphQlExecutionPipeline(GraphQlExecutionChain chain) {
return chain.pipeline();
}
/**
* The clock every deadline and expiry check reads, supplied only if the application has none.
*
* <p>Conditioned on the type rather than on this bean's name. Conditioned on the name it always
* created one, so an application that already had a {@code Clock} ended up with two and every
* injection point that wanted one failed to start — which is what happened the first time this
* platform shipped in the same context as the rest of the application, and could not have
* happened while it was build-only. An application's own bean wins; that is what
* auto-configuration is for.
*/
@Bean
@ConditionalOnMissingBean(Clock.class)
public Clock graphQlPlatformClock() {
return Clock.systemUTC();
}
/**
* The limits applied to a request when the adopter has not registered a client policy.
*
* <p>Page size, complexity and introspection follow {@code backend.graphql.*}; the rest are the
* calibration starting points from the design. An adopter replaces this bean rather than editing
* a table of constants.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlClientPolicy graphQlClientPolicy(GraphQlPlatformSettings properties) {
return GraphQlClientPolicy.defaults(
properties.limits().maximumPageSize(),
properties.limits().maximumComplexity(),
properties.console().introspectionEnabled());
}
/**
* How a request is authenticated.
*
* <p>Anonymous by default in a development mode, because authentication belongs to the
* composition root. What an anonymous caller may do is decided by the authorization policy and
* the client profile, both of which are checked on every request.
*
* <p>A production mode refuses anonymous callers outright, so the anonymous default there started
* an endpoint that answered every request with {@code AUTHENTICATION_REQUIRED}. That is the same
* missing composition decision as a missing authorization policy, and it fails the same way: at
* startup, by name.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlPrincipalResolver graphQlPrincipalResolver(GraphQlPlatformSettings properties) {
if (properties.deploymentMode() == null) {
throw new GraphQlPlatformConfigurationException(
List.of(GraphQlDeploymentMode.REQUIRED_MESSAGE));
}
if (properties.production()) {
throw new GraphQlPlatformConfigurationException(
List.of(
"backend.graphql.deployment-mode="
+ properties.deploymentMode()
+ " requires an explicit GraphQlPrincipalResolver bean; production refuses "
+ "anonymous callers, so the anonymous default would reject every request"));
}
return GraphQlPrincipalResolver.anonymous();
}
/** The only factory allowed to build a request context. */
@Bean
@ConditionalOnMissingBean
public GraphQlAuthenticationContextFactory graphQlAuthenticationContextFactory(
Clock graphQlPlatformClock) {
return new GraphQlAuthenticationContextFactory(graphQlPlatformClock);
}
/**
* Coordinate authorization rules.
*
* <p>There is no safe default here, so production does not get one. Coordinate rules are
* application knowledge: a deny-by-default skeleton policy would answer nothing and adopters
* would replace it with an allow-all one, while an allow-by-default policy shipped into
* production would be an unauthorized endpoint. So a development mode gets the permissive default
* that lets the schema be explored, and a production {@code backend.graphql.deployment-mode}
* refuses to start without an explicit policy.
*
* <p>Which mode that is comes from one setting. While the posture was split across a boolean and
* an enum, this bean read only the boolean — so a deployment declaring {@code PRODUCTION_PUBLIC}
* still received the permissive default.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlAuthorizationPolicy graphQlAuthorizationPolicy(GraphQlPlatformSettings properties) {
if (properties.deploymentMode() == null) {
throw new GraphQlPlatformConfigurationException(
List.of(GraphQlDeploymentMode.REQUIRED_MESSAGE));
}
if (properties.production()) {
throw new GraphQlPlatformConfigurationException(
List.of(
"backend.graphql.deployment-mode="
+ properties.deploymentMode()
+ " requires an explicit GraphQlAuthorizationPolicy bean; the platform has no "
+ "application coordinates to authorize on its own"));
}
return GraphQlAuthorizationPolicy.builder().denyByDefault(false).build();
}
/** Registered field costs; unregistered coordinates fall back to a conservative weight. */
@Bean
@ConditionalOnMissingBean
public GraphQlCostCatalog graphQlCostCatalog() {
return GraphQlCostCatalog.of();
}
/** Document structure measurement. */
@Bean
@ConditionalOnMissingBean
public GraphQlDocumentShapeAnalyzer graphQlDocumentShapeAnalyzer() {
return new GraphQlDocumentShapeAnalyzer();
}
/** Per-field pricing, driven by the page policy the client policy declares. */
@Bean
@ConditionalOnMissingBean
public GraphQlComplexityCalculator graphQlComplexityCalculator(
GraphQlCostCatalog catalog, GraphQlClientPolicy clientPolicy) {
return new GraphQlComplexityCalculator(
catalog, clientPolicy.defaultPageSize(), clientPolicy.maxPageSize());
}
/** Structural ceilings derived from the client policy. */
@Bean
@ConditionalOnMissingBean
public GraphQlStructuralLimitPolicy graphQlStructuralLimitPolicy(
GraphQlClientPolicy clientPolicy) {
return new GraphQlStructuralLimitPolicy(GraphQlStructuralLimits.from(clientPolicy));
}
/** The executable chain: select the operation, authorize it, judge its cost. */
@Bean
@ConditionalOnMissingBean
public GraphQlExecutionChain graphQlExecutionChain(
GraphQlClientPolicy clientPolicy,
GraphQlAuthorizationPolicy authorizationPolicy,
GraphQlDocumentShapeAnalyzer analyzer,
GraphQlStructuralLimitPolicy structuralLimits,
GraphQlComplexityCalculator calculator,
Clock graphQlPlatformClock) {
return GraphQlExecutionChain.stable(
new GraphQlOperationSelectionHandler(clientPolicy),
new GraphQlDocumentAuthorizationHandler(
new GraphQlAuthorizationInterceptor(authorizationPolicy), analyzer, clientPolicy),
new GraphQlCostBudgetHandler(
analyzer, structuralLimits, calculator, clientPolicy, graphQlPlatformClock));
}
/**
* Puts the chain on the real execution path.
*
* <p>Spring for GraphQL picks up every {@code Instrumentation} bean, so this is what turns the
* policy objects from a catalogue into something a request has to pass.
*/
@Bean
@ConditionalOnMissingBean(GraphQlPlatformInstrumentation.class)
public Instrumentation graphQlPlatformInstrumentation(
GraphQlExecutionChain chain, GraphQlWireErrorMapper errors) {
return new GraphQlPlatformInstrumentation(chain, errors);
}
/**
* The application's deliberate failure mappings.
*
* <p>Empty by default, which means every unrecognised failure is masked. An adopter replaces this
* bean to give its own modelled failures a stable code rather than an opaque internal error.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlExceptionResolver graphQlApplicationExceptionMappings() {
return GraphQlExceptionResolver.defaults();
}
/** The single vocabulary every client-visible error is produced from. */
@Bean
@ConditionalOnMissingBean
public GraphQlWireErrorMapper graphQlWireErrorMapper(GraphQlExceptionResolver mappings) {
return new GraphQlWireErrorMapper(mappings);
}
/** Adapts the mapper onto Spring's data-fetcher exception contract. */
@Bean
@ConditionalOnMissingBean(GraphQlDataFetcherExceptionResolver.class)
public DataFetcherExceptionResolver graphQlDataFetcherExceptionResolver(
GraphQlWireErrorMapper mapper) {
return new GraphQlDataFetcherExceptionResolver(mapper);
}
/** Shape ceilings for decoded {@code variables} and {@code extensions}. */
@Bean
@ConditionalOnMissingBean
public GraphQlJsonStructurePolicy graphQlJsonStructurePolicy(GraphQlClientPolicy clientPolicy) {
return GraphQlJsonStructurePolicy.from(clientPolicy);
}
/** Stable request-envelope extension allowlist. */
@Bean
@ConditionalOnMissingBean
public GraphQlExtensionsPolicy graphQlExtensionsPolicy() {
return GraphQlExtensionsPolicy.stableDefaults();
}
/** Establishes the request context on the real {@code /graphql} endpoint. */
@Bean
@ConditionalOnMissingBean(GraphQlPlatformWebInterceptor.class)
public WebGraphQlInterceptor graphQlPlatformWebInterceptor(
GraphQlPrincipalResolver principalResolver,
GraphQlAuthenticationContextFactory contextFactory,
GraphQlClientPolicy clientPolicy,
GraphQlJsonStructurePolicy structurePolicy,
GraphQlExtensionsPolicy extensionsPolicy,
GraphQlPlatformSettings properties,
Clock graphQlPlatformClock,
GraphQlWireErrorMapper errors) {
return new GraphQlPlatformWebInterceptor(
principalResolver,
contextFactory,
clientPolicy,
structurePolicy,
extensionsPolicy,
new GraphQlClientProfile(DEFAULT_ANONYMOUS_PROFILE),
TenantContext.system(DEFAULT_ANONYMOUS_TENANT),
properties.production(),
graphQlPlatformClock,
errors);
}
/** The approved scalar set; the wiring configurer refuses to wire anything absent from it. */
@Bean
@ConditionalOnMissingBean
public GraphQlScalarManifest graphQlScalarManifest() {
return GraphQlScalarManifest.of(
GraphQlScalarWiringConfigurer.stableScalars().keySet().stream()
.map(GraphQlScalarDefinition::named)
.toArray(GraphQlScalarDefinition[]::new));
}
/**
* Registers the approved custom scalars through Spring's supported wiring entry point.
*
* <p>Declared as the concrete type rather than as {@code RuntimeWiringConfigurer} so the startup
* check can ask it which scalars it will wire. Spring still picks it up as a configurer.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlScalarWiringConfigurer graphQlScalarWiringConfigurer(
GraphQlScalarManifest manifest) {
return new GraphQlScalarWiringConfigurer(manifest);
}
/** The metric attribute allowlist. */
@Bean
@ConditionalOnMissingBean
public GraphQlMetricCardinalityPolicy graphQlMetricCardinalityPolicy() {
return GraphQlMetricCardinalityPolicy.standard();
}
/** The sensitive-attribute filter. */
@Bean
@ConditionalOnMissingBean
public GraphQlSensitiveAttributeFilter graphQlSensitiveAttributeFilter(
GraphQlMetricCardinalityPolicy policy) {
return new GraphQlSensitiveAttributeFilter(policy);
}
/** The request observation convention. */
@Bean
@ConditionalOnMissingBean
public GraphQlRequestObservationConvention graphQlRequestObservationConvention(
GraphQlSensitiveAttributeFilter filter, GraphQlOperationNameCardinality operationNames) {
return new GraphQlRequestObservationConvention(filter, operationNames);
}
/**
* Hands the bounded request tags to Spring for GraphQL's observation instrumentation.
*
* <p>The convention above is a value; this is the bean Boot's {@code
* GraphQlObservationAutoConfiguration} looks for. Without it the framework falls back to its own
* convention and the platform's cardinality policy applies to nothing that is exported — the
* shape of defect where a control passes its tests and no request reaches it.
*
* @param convention the platform's bounded tag policy
*/
@Bean
@ConditionalOnMissingBean(ExecutionRequestObservationConvention.class)
public GraphQlRequestObservationConventionAdapter graphQlExecutionRequestObservationConvention(
GraphQlRequestObservationConvention convention) {
return new GraphQlRequestObservationConventionAdapter(convention);
}
/**
* Which operation names may become metric labels.
*
* <p>Defaults to the deployment's declared list, which is empty unless configured. Empty means
* every named operation collapses to one label: correct by default, and legible for any adopter
* who names the operations they care about.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlOperationNameCardinality graphQlOperationNameCardinality(
GraphQlPlatformSettings properties) {
return new GraphQlOperationNameCardinality(properties.observedOperationNames());
}
/** The resolver observation convention. */
@Bean
@ConditionalOnMissingBean
public GraphQlResolverObservationConvention graphQlResolverObservationConvention(
GraphQlSensitiveAttributeFilter filter) {
return new GraphQlResolverObservationConvention(filter);
}
/** The DataLoader observation convention. */
@Bean
@ConditionalOnMissingBean
public GraphQlDataLoaderObservationConvention graphQlDataLoaderObservationConvention(
GraphQlSensitiveAttributeFilter filter) {
return new GraphQlDataLoaderObservationConvention(filter);
}
/**
* The preparsed document cache bounds.
*
* <p>Idle expiry and both size bounds come from configuration rather than from a constant, so an
* adopter whose documents are large can trade entries for weight without forking the platform.
*/
@Bean
@ConditionalOnMissingBean
public GraphQlPreparsedCachePolicy graphQlPreparsedCachePolicy(
GraphQlPlatformSettings properties) {
return new GraphQlPreparsedCachePolicy(
properties.limits().preparsedCacheEntries(),
properties.limits().preparsedCacheWeight(),
properties.limits().preparsedCacheExpireAfterAccess());
}
/** The bounded parse/validate cache. */
@Bean
@ConditionalOnMissingBean
public BoundedPreparsedDocumentProvider<PreparsedDocumentEntry> graphQlPreparsedDocumentCache(
GraphQlPreparsedCachePolicy policy, Clock clock) {
return new BoundedPreparsedDocumentProvider<>(
policy, new GraphQlPreparsedCacheMetrics(), clock);
}
/**
* Hands the bounded cache to graphql-java, which is the only thing that consults one.
*
* <p>The schema hash is resolved through an {@code ObjectProvider} on first use: this customizer
* runs while the {@code GraphQlSource} is still being built, so asking for the schema here would
* be asking for the bean currently under construction.
*/
@Bean
@ConditionalOnMissingBean(name = "graphQlPreparsedDocumentCustomizer")
public GraphQlSourceBuilderCustomizer graphQlPreparsedDocumentCustomizer(
BoundedPreparsedDocumentProvider<PreparsedDocumentEntry> cache,
ObjectProvider<GraphQlSource> graphQlSource,
GraphQlPlatformSettings properties) {
GraphQlPreparsedDocumentAdapter adapter =
new GraphQlPreparsedDocumentAdapter(
cache, () -> schemaContractHash(graphQlSource), properties.validationPolicyVersion());
return builder ->
builder.configureGraphQl(graphQl -> graphQl.preparsedDocumentProvider(adapter));
}
/**
* The batch policies an adopter registers, empty until one does.
*
* <p>A bean rather than something each adopter constructs, because the two things downstream of
* it — the loader factory and the registrar — were beans nowhere, and a platform whose N+1
* protection has to be assembled by hand is a platform whose N+1 protection is not applied.
*
* @return the registry
*/
@Bean
@ConditionalOnMissingBean(
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry.class)
public dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry
graphQlBatchPolicyRegistry() {
return new dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry();
}
/**
* Supplies the per-loader batch policy and executor.
*
* @param policies the registered policies
* @param properties the platform settings, which supply the batch ceiling
* @param graphQlPlatformClock the clock deadlines are measured against
* @return the factory
*/
@Bean
@ConditionalOnMissingBean(
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory.class)
public dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory
graphQlDataLoaderFactory(
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlBatchPolicyRegistry policies,
GraphQlPlatformSettings properties,
Clock graphQlPlatformClock) {
// The page ceiling is the batch ceiling. Both answer the same question — how many rows one
// downstream call may ask for — and a batch limit larger than the page limit would let a single
// request fan out past the bound the same request already accepted for its page.
return new dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory(
policies, properties.limits().maximumPageSize(), graphQlPlatformClock);
}
/**
* Wraps an adopter's batch loader in the platform's chunking, budget and request scope.
*
* <p>This was the missing link. {@code GraphQlBatchLoaderRegistrar} existed, was tested, and was
* declared by no configuration — so a field resolving through {@code @BatchMapping} or a {@code
* DataLoader} met none of the platform's batch policy. The chunking and the budget were a set of
* well-tested objects no request could reach.
*
* <p>An adopter still supplies the downstream call, because only the adopter has one. What it no
* longer supplies is the machinery around it.
*
* @param factory the loader factory
* @return the registrar
*/
@Bean
@ConditionalOnMissingBean(
dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar.class)
public dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar
graphQlBatchLoaderRegistrar(
dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlDataLoaderFactory factory) {
return new dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlBatchLoaderRegistrar(factory);
}
private static String schemaContractHash(ObjectProvider<GraphQlSource> graphQlSource) {
GraphQlSource source = graphQlSource.getIfAvailable();
if (source == null) {
// A cache keyed on an unknown schema would survive a schema change, which is the one thing
// the schema part of the key exists to prevent. Partition it instead of guessing.
return "schema-unavailable";
}
return GraphQlPreparsedDocumentAdapter.sha256(new SchemaPrinter().print(source.schema()));
}
}
@@ -0,0 +1,74 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.execution.BoundedPreparsedDocumentProvider;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCacheMetrics;
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlPreparsedCachePolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPreparsedDocumentAdapter;
import graphql.execution.preparsed.PreparsedDocumentEntry;
import graphql.schema.idl.SchemaPrinter;
import java.time.Clock;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.graphql.autoconfigure.GraphQlSourceBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.execution.GraphQlSource;
/** The bounded parse/validate cache and its hand-off to graphql-java. */
@Configuration(proxyBeanMethods = false)
class GraphQlPreparsedCacheConfiguration {
/**
* The preparsed document cache bounds.
*
* <p>Idle expiry and both size bounds come from configuration rather than from a constant, so an
* adopter whose documents are large can trade entries for weight without forking the platform.
*/
@Bean
@ConditionalOnMissingBean
GraphQlPreparsedCachePolicy graphQlPreparsedCachePolicy(GraphQlPlatformSettings properties) {
return new GraphQlPreparsedCachePolicy(
properties.limits().preparsedCacheEntries(),
properties.limits().preparsedCacheWeight(),
properties.limits().preparsedCacheExpireAfterAccess());
}
/** The bounded parse/validate cache. */
@Bean
@ConditionalOnMissingBean
BoundedPreparsedDocumentProvider<PreparsedDocumentEntry> graphQlPreparsedDocumentCache(
GraphQlPreparsedCachePolicy policy, Clock clock) {
return new BoundedPreparsedDocumentProvider<>(
policy, new GraphQlPreparsedCacheMetrics(), clock);
}
/**
* Hands the bounded cache to graphql-java, which is the only thing that consults one.
*
* <p>The schema hash is resolved through an {@code ObjectProvider} on first use: this customizer
* runs while the {@code GraphQlSource} is still being built, so asking for the schema here would
* be asking for the bean currently under construction.
*/
@Bean
@ConditionalOnMissingBean(name = "graphQlPreparsedDocumentCustomizer")
GraphQlSourceBuilderCustomizer graphQlPreparsedDocumentCustomizer(
BoundedPreparsedDocumentProvider<PreparsedDocumentEntry> cache,
ObjectProvider<GraphQlSource> graphQlSource,
GraphQlPlatformSettings properties) {
GraphQlPreparsedDocumentAdapter adapter =
new GraphQlPreparsedDocumentAdapter(
cache, () -> schemaContractHash(graphQlSource), properties.validationPolicyVersion());
return builder ->
builder.configureGraphQl(graphQl -> graphQl.preparsedDocumentProvider(adapter));
}
private static String schemaContractHash(ObjectProvider<GraphQlSource> graphQlSource) {
GraphQlSource source = graphQlSource.getIfAvailable();
if (source == null) {
// A cache keyed on an unknown schema would survive a schema change, which is the one thing
// the schema part of the key exists to prevent. Partition it instead of guessing.
return "schema-unavailable";
}
return GraphQlPreparsedDocumentAdapter.sha256(new SchemaPrinter().print(source.schema()));
}
}
@@ -0,0 +1,62 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.servlet.GraphQlRequestBodyLimitFilter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.graphql.autoconfigure.GraphQlProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
/**
* Caps the raw request body upstream of the JSON decoder, on a servlet stack.
*
* <p>Loaded only where servlets exist. The leaf takes the servlet API as {@code compileOnly}, so on
* a non-web application this class is simply not on the classpath and the condition never matches —
* which is why the guard is {@code @ConditionalOnClass} as well as
* {@code @ConditionalOnWebApplication}.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = "jakarta.servlet.Filter")
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
class GraphQlRequestBodyLimitConfiguration {
/** Slack for the JSON envelope around the three sized fields. */
static final int ENVELOPE_FRAMING_ALLOWANCE_BYTES = 1024;
/**
* Registers the cap with the highest precedence.
*
* <p>The whole point is to run before anything reads the body, so it has to precede the decoder,
* Spring Security's filters and any application filter that might buffer the request.
*/
@Bean
@ConditionalOnMissingBean
FilterRegistrationBean<GraphQlRequestBodyLimitFilter> graphQlRequestBodyLimitFilter(
GraphQlClientPolicy clientPolicy, ObjectProvider<GraphQlProperties> frameworkProperties) {
// The body carries the document, the variables and the extensions plus JSON framing, so the
// cap is their sum with room for the envelope rather than any one of them.
long maxBodyBytes =
(long) clientPolicy.maxDocumentBytes()
+ clientPolicy.maxVariablesBytes()
+ clientPolicy.maxVariablesBytes()
+ ENVELOPE_FRAMING_ALLOWANCE_BYTES;
// The endpoint path follows the framework when the framework is there. It is optional because
// the platform can be assembled without Boot's GraphQL auto-configuration — a slice test, or a
// composition root that wires the endpoint itself — and a cap that refuses to exist in those
// contexts would make the leaf harder to test than to secure.
String path = frameworkProperties.getIfAvailable(GraphQlProperties::new).getHttp().getPath();
FilterRegistrationBean<GraphQlRequestBodyLimitFilter> registration =
new FilterRegistrationBean<>(new GraphQlRequestBodyLimitFilter(path, maxBodyBytes));
registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
registration.addUrlPatterns(path);
return registration;
}
}
@@ -0,0 +1,133 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.api.GraphQlClientProfile;
import dev.caskeleton.adapter.inbound.graphql.context.TenantContext;
import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlExtensionsPolicy;
import dev.caskeleton.adapter.inbound.graphql.http.GraphQlJsonStructurePolicy;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPlatformWebInterceptor;
import dev.caskeleton.adapter.inbound.graphql.runtime.GraphQlPrincipalResolver;
import dev.caskeleton.adapter.inbound.graphql.security.GraphQlAuthenticationContextFactory;
import java.time.Clock;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.graphql.server.WebGraphQlInterceptor;
/**
* The request's policy and context: the client policy, request-shape bounds, how a caller is
* authenticated, and the transport interceptor that turns those into the request context every
* downstream stage reads.
*/
@Configuration(proxyBeanMethods = false)
class GraphQlRequestContextConfiguration {
/**
* The clock every deadline and expiry check reads, supplied only if the application has none.
*
* <p>Conditioned on the type rather than on this bean's name. Conditioned on the name it always
* created one, so an application that already had a {@code Clock} ended up with two and every
* injection point that wanted one failed to start. An application's own bean wins; that is what
* auto-configuration is for.
*/
@Bean
@ConditionalOnMissingBean(Clock.class)
Clock graphQlPlatformClock() {
return Clock.systemUTC();
}
/**
* The limits applied to a request when the adopter has not registered a client policy.
*
* <p>Page size, complexity and introspection follow {@code backend.graphql.*}; the rest are the
* calibration starting points from the design. An adopter replaces this bean rather than editing
* a table of constants.
*/
@Bean
@ConditionalOnMissingBean
GraphQlClientPolicy graphQlClientPolicy(GraphQlPlatformSettings properties) {
return GraphQlClientPolicy.defaults(
properties.limits().maximumPageSize(),
properties.limits().maximumComplexity(),
properties.console().introspectionEnabled());
}
/**
* How a request is authenticated.
*
* <p>Anonymous by default in a development mode, because authentication belongs to the
* composition root. What an anonymous caller may do is decided by the authorization policy and
* the client profile, both of which are checked on every request.
*
* <p>A production mode refuses anonymous callers outright, so the anonymous default there started
* an endpoint that answered every request with {@code AUTHENTICATION_REQUIRED}. That is the same
* missing composition decision as a missing authorization policy, and it fails the same way: at
* startup, by name.
*/
@Bean
@ConditionalOnMissingBean
GraphQlPrincipalResolver graphQlPrincipalResolver(GraphQlPlatformSettings properties) {
if (properties.deploymentMode() == null) {
throw new GraphQlPlatformConfigurationException(
List.of(GraphQlDeploymentMode.REQUIRED_MESSAGE));
}
if (properties.production()) {
throw new GraphQlPlatformConfigurationException(
List.of(
"backend.graphql.deployment-mode="
+ properties.deploymentMode()
+ " requires an explicit GraphQlPrincipalResolver bean; production refuses "
+ "anonymous callers, so the anonymous default would reject every request"));
}
return GraphQlPrincipalResolver.anonymous();
}
/** The only factory allowed to build a request context. */
@Bean
@ConditionalOnMissingBean
GraphQlAuthenticationContextFactory graphQlAuthenticationContextFactory(
Clock graphQlPlatformClock) {
return new GraphQlAuthenticationContextFactory(graphQlPlatformClock);
}
/** Shape ceilings for decoded {@code variables} and {@code extensions}. */
@Bean
@ConditionalOnMissingBean
GraphQlJsonStructurePolicy graphQlJsonStructurePolicy(GraphQlClientPolicy clientPolicy) {
return GraphQlJsonStructurePolicy.from(clientPolicy);
}
/** Stable request-envelope extension allowlist. */
@Bean
@ConditionalOnMissingBean
GraphQlExtensionsPolicy graphQlExtensionsPolicy() {
return GraphQlExtensionsPolicy.stableDefaults();
}
/** Establishes the request context on the real {@code /graphql} endpoint. */
@Bean
@ConditionalOnMissingBean(GraphQlPlatformWebInterceptor.class)
WebGraphQlInterceptor graphQlPlatformWebInterceptor(
GraphQlPrincipalResolver principalResolver,
GraphQlAuthenticationContextFactory contextFactory,
GraphQlClientPolicy clientPolicy,
GraphQlJsonStructurePolicy structurePolicy,
GraphQlExtensionsPolicy extensionsPolicy,
GraphQlPlatformSettings properties,
Clock graphQlPlatformClock,
GraphQlWireErrorMapper errors) {
return new GraphQlPlatformWebInterceptor(
principalResolver,
contextFactory,
clientPolicy,
structurePolicy,
extensionsPolicy,
new GraphQlClientProfile(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_PROFILE),
TenantContext.system(GraphQlPlatformAutoConfiguration.DEFAULT_ANONYMOUS_TENANT),
properties.production(),
graphQlPlatformClock,
errors);
}
}
@@ -25,7 +25,16 @@ import org.springframework.context.annotation.Import;
matchIfMissing = true)
@EnableConfigurationProperties(GraphQlPlatformSettings.class)
@Import({
// One configuration per capability; GraphQlPlatformAutoConfiguration holds the startup check.
GraphQlPlatformAutoConfiguration.class,
GraphQlRequestContextConfiguration.class,
GraphQlExecutionChainConfiguration.class,
GraphQlErrorConfiguration.class,
GraphQlScalarConfiguration.class,
GraphQlObservationConfiguration.class,
GraphQlPreparsedCacheConfiguration.class,
GraphQlDataLoaderConfiguration.class,
GraphQlRequestBodyLimitConfiguration.class,
// The resolver for the schema's only field. It is a @Controller in a package the composition
// root's component scan excludes by regex — the exclusion that makes this capability optional —
// and no root imported it, so a deployment with GraphQL on served a schema declaring
@@ -0,0 +1,35 @@
package dev.caskeleton.adapter.inbound.graphql.autoconfigure;
import dev.caskeleton.adapter.inbound.graphql.scalar.GraphQlScalarWiringConfigurer;
import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarDefinition;
import dev.caskeleton.adapter.inbound.graphql.schema.GraphQlScalarManifest;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** The approved custom scalars and their wiring. */
@Configuration(proxyBeanMethods = false)
class GraphQlScalarConfiguration {
/** The approved scalar set; the wiring configurer refuses to wire anything absent from it. */
@Bean
@ConditionalOnMissingBean
GraphQlScalarManifest graphQlScalarManifest() {
return GraphQlScalarManifest.of(
GraphQlScalarWiringConfigurer.stableScalars().keySet().stream()
.map(GraphQlScalarDefinition::named)
.toArray(GraphQlScalarDefinition[]::new));
}
/**
* Registers the approved custom scalars through Spring's supported wiring entry point.
*
* <p>Declared as the concrete type rather than as {@code RuntimeWiringConfigurer} so the startup
* check can ask it which scalars it will wire. Spring still picks it up as a configurer.
*/
@Bean
@ConditionalOnMissingBean
GraphQlScalarWiringConfigurer graphQlScalarWiringConfigurer(GraphQlScalarManifest manifest) {
return new GraphQlScalarWiringConfigurer(manifest);
}
}
@@ -164,15 +164,24 @@ public final class BoundedPreparsedDocumentProvider<D> {
}
}
/**
* Drops idle entries from the least-recently-accessed end and stops at the first live one.
*
* <p>The map is access-ordered, so every entry after a live one was touched later and is live
* too; walking on would only re-check them under the lock on every lookup. Timestamps are read
* before the lock is taken, so two racing accesses can land a few microseconds out of order — the
* cost is that such an entry leaves on a later pass, never that a live entry is dropped.
*/
private void expireIdle(Instant now) {
var entries = cache.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<GraphQlPreparsedCacheKey, Entry<D>> entry = entries.next();
if (!now.isBefore(entry.getValue().lastAccessAt().plus(policy.expireAfterAccess()))) {
weight -= entry.getValue().weight();
entries.remove();
metrics.recordExpiry();
if (now.isBefore(entry.getValue().lastAccessAt().plus(policy.expireAfterAccess()))) {
return;
}
weight -= entry.getValue().weight();
entries.remove();
metrics.recordExpiry();
}
}
@@ -1,46 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.http;
import java.util.Map;
/**
* The four request fields the GraphQL over HTTP profile defines.
*
* <p>{@code variables} and {@code extensions} are maps rather than free JSON: the profile says they
* are objects, and accepting an array or a scalar there is how a client discovers an unintended
* code path.
*
* @param query the GraphQL document
* @param operationName selected operation name, or {@code null}
* @param variables variable values, never {@code null}, null entries preserved
* @param extensions protocol extensions, never {@code null}, null entries preserved
*/
public record GraphQlHttpRequestEnvelope(
String query,
String operationName,
Map<String, Object> variables,
Map<String, Object> extensions) {
public GraphQlHttpRequestEnvelope {
// Deep and null-preserving. `Map.copyOf` threw on `{"id": null}` — a legal variables object
// whose explicit null is a different instruction from omitting the key — and left nested maps
// and lists shared with the decoder, so the value a validator checked was not necessarily the
// value an executor later read.
variables = GraphQlJsonValues.immutableObject(variables);
extensions = GraphQlJsonValues.immutableObject(extensions);
}
/** An envelope carrying only a document. */
public static GraphQlHttpRequestEnvelope of(String query) {
return new GraphQlHttpRequestEnvelope(query, null, Map.of(), Map.of());
}
/** An envelope carrying a named operation. */
public static GraphQlHttpRequestEnvelope of(String query, String operationName) {
return new GraphQlHttpRequestEnvelope(query, operationName, Map.of(), Map.of());
}
/** Whether a document was supplied at all. */
public boolean hasQuery() {
return query != null && !query.isBlank();
}
}
@@ -1,152 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.http;
import dev.caskeleton.adapter.inbound.graphql.api.GraphQlOperationName;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import java.util.Map;
/**
* Enforces the pre-parse limits of the Stable HTTP profile (design §9.2, §18).
*
* <p>Everything here runs <em>before</em> the GraphQL parser sees the document. That ordering is
* the point: a parser has to allocate proportionally to its input, so a size limit applied
* afterwards has already paid the cost it was supposed to prevent.
*
* <p>Diagnostics report byte counts and field names only — never the document, a variable or an
* extension value.
*/
public final class GraphQlRequestEnvelopeValidator {
private final int maxDocumentBytes;
private final int maxVariablesBytes;
private final int maxExtensionsBytes;
private final boolean namedOperationRequired;
private final GraphQlExtensionsPolicy extensionsPolicy;
private GraphQlRequestEnvelopeValidator(
int maxDocumentBytes,
int maxVariablesBytes,
int maxExtensionsBytes,
boolean namedOperationRequired,
GraphQlExtensionsPolicy extensionsPolicy) {
if (maxDocumentBytes < 1 || maxVariablesBytes < 1 || maxExtensionsBytes < 1) {
throw new IllegalArgumentException("request size limits must be positive");
}
this.maxDocumentBytes = maxDocumentBytes;
this.maxVariablesBytes = maxVariablesBytes;
this.maxExtensionsBytes = maxExtensionsBytes;
this.namedOperationRequired = namedOperationRequired;
this.extensionsPolicy = extensionsPolicy;
}
/** A validator that only bounds the variables size, for focused checks. */
public static GraphQlRequestEnvelopeValidator maxVariablesBytes(int value) {
return new GraphQlRequestEnvelopeValidator(
Integer.MAX_VALUE,
value,
Integer.MAX_VALUE,
false,
GraphQlExtensionsPolicy.stableDefaults());
}
/** A validator derived from a client policy. */
public static GraphQlRequestEnvelopeValidator forPolicy(GraphQlClientPolicy policy) {
return forPolicy(policy, GraphQlExtensionsPolicy.stableDefaults());
}
/** A validator derived from a client policy with an explicit extensions allowlist. */
public static GraphQlRequestEnvelopeValidator forPolicy(
GraphQlClientPolicy policy, GraphQlExtensionsPolicy extensionsPolicy) {
return new GraphQlRequestEnvelopeValidator(
policy.maxDocumentBytes(),
policy.maxVariablesBytes(),
policy.maxVariablesBytes(),
policy.namedOperationRequired(),
extensionsPolicy);
}
/**
* Validates the serialized variables size.
*
* @throws GraphQlRequestTooLargeException when the limit is exceeded
*/
public void validateVariables(byte[] bytes) {
if (bytes != null && bytes.length > maxVariablesBytes) {
throw new GraphQlRequestTooLargeException(
"variables too large", bytes.length, maxVariablesBytes);
}
}
/**
* Validates the serialized document size.
*
* @throws GraphQlRequestTooLargeException when the limit is exceeded
*/
public void validateDocument(byte[] bytes) {
if (bytes != null && bytes.length > maxDocumentBytes) {
throw new GraphQlRequestTooLargeException(
"document too large", bytes.length, maxDocumentBytes);
}
}
/**
* Validates the serialized extensions size.
*
* @throws GraphQlRequestTooLargeException when the limit is exceeded
*/
public void validateExtensions(byte[] bytes) {
if (bytes != null && bytes.length > maxExtensionsBytes) {
throw new GraphQlRequestTooLargeException(
"extensions too large", bytes.length, maxExtensionsBytes);
}
}
/**
* Validates measured sizes together.
*
* @throws GraphQlRequestTooLargeException when any limit is exceeded
*/
public void validateSize(GraphQlRequestSize size) {
if (size.documentBytes() > maxDocumentBytes) {
throw new GraphQlRequestTooLargeException(
"document too large", size.documentBytes(), maxDocumentBytes);
}
if (size.variablesBytes() > maxVariablesBytes) {
throw new GraphQlRequestTooLargeException(
"variables too large", size.variablesBytes(), maxVariablesBytes);
}
if (size.extensionsBytes() > maxExtensionsBytes) {
throw new GraphQlRequestTooLargeException(
"extensions too large", size.extensionsBytes(), maxExtensionsBytes);
}
}
/**
* Validates the parsed envelope's structure and operation naming.
*
* @throws GraphQlRequestFormatException when the document is missing, an unregistered extension
* key is present, or a named operation is required and absent
*/
public void validateEnvelope(GraphQlHttpRequestEnvelope envelope) {
if (envelope == null || !envelope.hasQuery()) {
throw new GraphQlRequestFormatException("query is required");
}
extensionsPolicy.verify(envelope.extensions());
if (namedOperationRequired && GraphQlOperationName.parse(envelope.operationName()).isEmpty()) {
throw new GraphQlRequestFormatException("operationName is required for this client profile");
}
}
/**
* Validates that a raw JSON value destined for {@code variables} or {@code extensions} is an
* object.
*
* @param field field name, used in the diagnostic
* @param value the decoded value
* @throws GraphQlRequestFormatException when the value is present but not an object
*/
public static void requireJsonObject(String field, Object value) {
if (value != null && !(value instanceof Map)) {
throw new GraphQlRequestFormatException(field + " must be a JSON object");
}
}
}
@@ -8,6 +8,7 @@ import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
@@ -175,6 +176,31 @@ class BoundedPreparsedDocumentProviderTest {
.hasValue(1);
}
@Test
void aReaccessedEntryOutlivesAnOlderIdleOneEvenWhenItWasCachedFirst() {
// given
var clock = new MutableClock(NOW);
var provider =
new BoundedPreparsedDocumentProvider<String>(
new GraphQlPreparsedCachePolicy(100, 10_000, Duration.ofMinutes(10)),
new GraphQlPreparsedCacheMetrics(),
clock);
var first = new GraphQlPreparsedCacheKey("first", "schema-a", "policy-1", "FIRST_PARTY");
var second = new GraphQlPreparsedCacheKey("second", "schema-a", "policy-1", "FIRST_PARTY");
provider.getDocument(first, 10, ignored -> "first");
clock.advance(Duration.ofMinutes(6));
provider.getDocument(second, 10, ignored -> "second");
clock.advance(Duration.ofMinutes(2));
provider.getDocument(first, 10, ignored -> "first-reparsed");
clock.advance(Duration.ofMinutes(9));
// when
int size = provider.size();
// then
assertThat(List.of(size, provider.metrics().expiries())).containsExactly(1, 1L);
}
@Test
void concurrentMissesOnOneKeyParseOnce() throws Exception {
var provider =
@@ -3,6 +3,7 @@ package dev.caskeleton.adapter.inbound.graphql.http;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import java.util.ArrayList;
@@ -16,9 +17,11 @@ import org.junit.jupiter.api.Test;
* The pre-execution bounds on a decoded request, and what they must not break.
*
* <p>Two failures sat next to each other here. Sizes were measured in characters, which lets a
* multi-byte document cost several times the limit it passed. And the envelope copied its inputs
* with {@code Map.copyOf}, which throws on a null value — so {@code {"id": null}}, a legal
* variables object with a meaning distinct from omitting the key, failed the request outright.
* multi-byte document cost several times the limit it passed. And the request copy used {@code
* Map.copyOf}, which throws on a null value — so {@code {"id": null}}, a legal variables object
* with a meaning distinct from omitting the key, failed the request outright. The byte limits
* themselves are tested on the interceptor that enforces them ({@code
* GraphQlPlatformWebInterceptorRequestBoundsTest}).
*/
class GraphQlRequestBoundsTest {
@@ -32,49 +35,24 @@ class GraphQlRequestBoundsTest {
.isEqualTo(6);
}
@Test
void theExactLimitPassesAndOneByteMoreDoesNot() {
GraphQlRequestEnvelopeValidator validator =
GraphQlRequestEnvelopeValidator.maxVariablesBytes(8);
assertThatCode(() -> validator.validateVariables(new byte[8])).doesNotThrowAnyException();
assertThatThrownBy(() -> validator.validateVariables(new byte[9]))
.isInstanceOf(GraphQlRequestTooLargeException.class);
}
@Test
void theExactLimitPassesAndOneByteMoreDoesNotForMultiByteText() {
// Six characters of three UTF-8 bytes each.
String eighteenBytes = "요청요청요청";
GraphQlRequestEnvelopeValidator validator =
GraphQlRequestEnvelopeValidator.maxVariablesBytes(18);
assertThat(GraphQlRequestSize.ofDocument(eighteenBytes).documentBytes()).isEqualTo(18);
assertThatCode(() -> validator.validateVariables(new byte[18])).doesNotThrowAnyException();
assertThatThrownBy(() -> validator.validateVariables(new byte[19]))
.isInstanceOf(GraphQlRequestTooLargeException.class);
}
@Test
void anExplicitNullVariableSurvivesTheEnvelopeCopy() {
Map<String, Object> variables = new HashMap<>();
variables.put("id", null);
GraphQlHttpRequestEnvelope envelope =
new GraphQlHttpRequestEnvelope("{ q }", null, variables, Map.of());
Map<String, Object> envelope = GraphQlJsonValues.immutableObject(variables);
assertThat(envelope.variables()).containsKey("id");
assertThat(envelope.variables().get("id")).isNull();
assertThat(envelope).containsEntry("id", null);
}
@SuppressWarnings("unchecked")
private static List<Object> listAt(GraphQlHttpRequestEnvelope envelope, String key) {
return (List<Object>) envelope.variables().get(key);
private static List<Object> listAt(Map<String, Object> envelope, String key) {
return (List<Object>) envelope.get(key);
}
@SuppressWarnings("unchecked")
private static Map<String, Object> objectAt(GraphQlHttpRequestEnvelope envelope, String key) {
return (Map<String, Object>) envelope.variables().get(key);
private static Map<String, Object> objectAt(Map<String, Object> envelope, String key) {
return (Map<String, Object>) envelope.get(key);
}
@Test
@@ -85,8 +63,7 @@ class GraphQlRequestBoundsTest {
variables.put("filter", filter);
variables.put("ids", java.util.Arrays.asList("a", null));
GraphQlHttpRequestEnvelope envelope =
new GraphQlHttpRequestEnvelope("{ q }", null, variables, Map.of());
Map<String, Object> envelope = GraphQlJsonValues.immutableObject(variables);
Map<String, Object> copiedFilter = objectAt(envelope, "filter");
assertThat(copiedFilter).containsKey("status");
@@ -103,8 +80,7 @@ class GraphQlRequestBoundsTest {
variables.put("filter", filter);
variables.put("ids", ids);
GraphQlHttpRequestEnvelope envelope =
new GraphQlHttpRequestEnvelope("{ q }", null, variables, Map.of());
Map<String, Object> envelope = GraphQlJsonValues.immutableObject(variables);
filter.put("status", "CLOSED");
ids.add("b");
@@ -117,8 +93,7 @@ class GraphQlRequestBoundsTest {
void theEnvelopeCopyIsUnmodifiableAllTheWayDown() {
Map<String, Object> variables = Map.of("filter", new LinkedHashMap<>(Map.of("status", "OPEN")));
GraphQlHttpRequestEnvelope envelope =
new GraphQlHttpRequestEnvelope("{ q }", null, variables, Map.of());
Map<String, Object> envelope = GraphQlJsonValues.immutableObject(variables);
Map<String, Object> copiedFilter = objectAt(envelope, "filter");
assertThatThrownBy(() -> copiedFilter.put("status", "CLOSED"))
@@ -170,4 +145,45 @@ class GraphQlRequestBoundsTest {
.as("brackets, two single-digit numbers, one comma")
.isEqualTo(5);
}
@Test
void aUtf8DocumentOfTwoCharactersCountsAsSixBytesAndTheTotalAddsEveryField() {
// when
GraphQlRequestSize size = GraphQlRequestSize.of("쿼리", "{}", "{}");
// then
assertThat(size)
.extracting(GraphQlRequestSize::documentBytes, GraphQlRequestSize::total)
.containsExactly(6, 10);
}
@Test
void stableDefaultsRegisterNoExtensionKey() {
assertThat(GraphQlExtensionsPolicy.stableDefaults().allowedKeys()).isEmpty();
}
@Test
void stableDefaultsRejectAnIdempotencyKeyExtensionAsUnregistered() {
// given
GraphQlExtensionsPolicy policy = GraphQlExtensionsPolicy.stableDefaults();
// when
Throwable thrown = catchThrowable(() -> policy.verify(Map.of("idempotencyKey", "request-1")));
// then
assertThat(thrown)
.isInstanceOf(GraphQlRequestFormatException.class)
.hasMessage("unregistered GraphQL extensions key(s): [idempotencyKey]");
}
@Test
void aRegisteredExtensionKeyDoesNotThrow() {
// given
GraphQlExtensionsPolicy policy =
GraphQlExtensionsPolicy.allowing(GraphQlExtensionsPolicy.PERSISTED_QUERY);
// when & then
assertThatCode(() -> policy.verify(Map.of(GraphQlExtensionsPolicy.PERSISTED_QUERY, Map.of())))
.doesNotThrowAnyException();
}
}
@@ -1,150 +0,0 @@
package dev.caskeleton.adapter.inbound.graphql.http;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
/** Pre-parse request envelope, size and extensions limits (Stable plan Task 16). */
class GraphQlRequestEnvelopeValidatorTest {
@Test
void rejectsOversizedVariables() {
var validator = GraphQlRequestEnvelopeValidator.maxVariablesBytes(16);
assertThatThrownBy(
() ->
validator.validateVariables(
"{\"value\":\"01234567890123456789\"}".getBytes(StandardCharsets.UTF_8)))
.isInstanceOf(GraphQlRequestTooLargeException.class);
}
@Test
void sizeDiagnosticsReportByteCountsAndNeverContent() {
var validator = GraphQlRequestEnvelopeValidator.maxVariablesBytes(8);
String secret = "{\"card\":\"4111111111111111\"}";
assertThatThrownBy(() -> validator.validateVariables(secret.getBytes(StandardCharsets.UTF_8)))
.isInstanceOf(GraphQlRequestTooLargeException.class)
.hasMessageContaining("> 8 bytes")
.hasMessageNotContaining("4111");
}
@Test
void rejectsOversizedDocumentBeforeParsing() {
var validator = GraphQlRequestEnvelopeValidator.forPolicy(policy(32, true));
assertThatThrownBy(
() ->
validator.validateSize(
GraphQlRequestSize.ofDocument("query Big { " + "x".repeat(64) + " }")))
.isInstanceOf(GraphQlRequestTooLargeException.class)
.hasMessageContaining("document too large");
}
@Test
void variablesAndExtensionsMustBeJsonObjects() {
assertThatThrownBy(
() -> GraphQlRequestEnvelopeValidator.requireJsonObject("variables", List.of(1, 2)))
.isInstanceOf(GraphQlRequestFormatException.class)
.hasMessageContaining("variables must be a JSON object");
assertThatCode(() -> GraphQlRequestEnvelopeValidator.requireJsonObject("extensions", null))
.doesNotThrowAnyException();
assertThatCode(() -> GraphQlRequestEnvelopeValidator.requireJsonObject("variables", Map.of()))
.doesNotThrowAnyException();
}
@Test
void stableDefaultsRegisterNoExtensionKey() {
assertThat(GraphQlExtensionsPolicy.stableDefaults().allowedKeys()).isEmpty();
}
@Test
void stableDefaultsRejectAnIdempotencyKeyExtensionAsUnregistered() {
// given
GraphQlExtensionsPolicy policy = GraphQlExtensionsPolicy.stableDefaults();
// when
Throwable thrown = catchThrowable(() -> policy.verify(Map.of("idempotencyKey", "request-1")));
// then
assertThat(thrown)
.isInstanceOf(GraphQlRequestFormatException.class)
.hasMessage("unregistered GraphQL extensions key(s): [idempotencyKey]");
}
@Test
void aRegisteredExtensionKeyDoesNotThrow() {
// given
GraphQlExtensionsPolicy policy =
GraphQlExtensionsPolicy.allowing(GraphQlExtensionsPolicy.PERSISTED_QUERY);
// when & then
assertThatCode(() -> policy.verify(Map.of(GraphQlExtensionsPolicy.PERSISTED_QUERY, Map.of())))
.doesNotThrowAnyException();
}
@Test
void productionClientPolicyEnforcesANamedOperation() {
var validator = GraphQlRequestEnvelopeValidator.forPolicy(policy(65536, true));
assertThatThrownBy(
() -> validator.validateEnvelope(GraphQlHttpRequestEnvelope.of("query { ping }")))
.isInstanceOf(GraphQlRequestFormatException.class)
.hasMessageContaining("operationName is required");
assertThatCode(
() ->
validator.validateEnvelope(
GraphQlHttpRequestEnvelope.of("query Ping { ping }", "Ping")))
.doesNotThrowAnyException();
}
@Test
void anonymousOperationIsAllowedWhenThePolicyDoesNotRequireAName() {
var validator = GraphQlRequestEnvelopeValidator.forPolicy(policy(65536, false));
assertThatCode(
() -> validator.validateEnvelope(GraphQlHttpRequestEnvelope.of("query { ping }")))
.doesNotThrowAnyException();
}
@Test
void missingDocumentIsAFormatError() {
var validator = GraphQlRequestEnvelopeValidator.forPolicy(policy(65536, false));
assertThatThrownBy(() -> validator.validateEnvelope(GraphQlHttpRequestEnvelope.of(" ")))
.isInstanceOf(GraphQlRequestFormatException.class);
}
@Test
void requestSizeMeasuresUtf8Bytes() {
GraphQlRequestSize size = GraphQlRequestSize.of("쿼리", "{}", "{}");
assertThat(size.documentBytes()).isEqualTo(6);
assertThat(size.total()).isEqualTo(10);
}
private static GraphQlClientPolicy policy(int documentBytes, boolean namedOperationRequired) {
return new GraphQlClientPolicy(
documentBytes,
65536,
12,
500,
50,
50,
1000,
20,
100,
10000,
Duration.ofSeconds(5),
false,
namedOperationRequired);
}
}
@@ -0,0 +1,169 @@
package dev.caskeleton.adapter.inbound.graphql.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlRootAutoConfiguration;
import dev.caskeleton.adapter.inbound.graphql.policy.GraphQlClientPolicy;
import java.net.URI;
import java.time.Duration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
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.graphql.ResponseError;
import org.springframework.graphql.server.WebGraphQlInterceptor;
import org.springframework.graphql.server.WebGraphQlRequest;
import org.springframework.graphql.server.WebGraphQlResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import reactor.core.publisher.Mono;
/**
* The pre-execution bounds the real {@code /graphql} endpoint applies, driven through the
* auto-configured {@link GraphQlPlatformWebInterceptor}.
*
* <p>These replace the tests of a parallel envelope validator that no request ever reached: the
* bounds that matter are the ones this interceptor enforces, so this is what the tests call.
*/
class GraphQlPlatformWebInterceptorRequestBoundsTest {
private static final int MAX_DOCUMENT_BYTES = 32;
private static final int MAX_VARIABLES_BYTES = 18;
private final ApplicationContextRunner runner =
new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(GraphQlRootAutoConfiguration.class))
.withPropertyValues(
"backend.graphql.enabled=true", "backend.graphql.deployment-mode=LOCAL")
.withBean(
GraphQlClientPolicy.class,
() ->
new GraphQlClientPolicy(
MAX_DOCUMENT_BYTES,
MAX_VARIABLES_BYTES,
3,
500,
50,
50,
3,
20,
100,
10_000,
Duration.ofSeconds(5),
false,
false));
@Test
void aDocumentOverTheByteLimitIsRejectedWithoutReachingExecution() {
// given
String document = "query Big { " + "x".repeat(64) + " }";
// when
Outcome outcome = intercept(document, Map.of(), Map.of());
// then
assertThat(outcome)
.extracting(Outcome::executed, Outcome::code)
.containsExactly(false, "PAYLOAD_TOO_LARGE");
}
@Test
@DisplayName("한글 6자(18 bytes) 변수는 문자 수가 아니라 UTF-8 byte 로 재서 한도 18 을 넘는다")
void variablesAreMeasuredInUtf8BytesNotCharacters() {
// given
Map<String, Object> variables = Map.of("v", "요청요청요청");
// when
Outcome outcome = intercept("{ _health }", variables, Map.of());
// then
assertThat(outcome)
.extracting(Outcome::executed, Outcome::code)
.containsExactly(false, "PAYLOAD_TOO_LARGE");
}
@Test
void variablesAtTheByteLimitReachExecution() {
// given
Map<String, Object> variables = Map.of("v", "0123456789");
// when
Outcome outcome = intercept("{ _health }", variables, Map.of());
// then
assertThat(outcome.executed()).isTrue();
}
@Test
void aTooDeeplyNestedVariableIsRejectedAsAShapeViolation() {
// given
Map<String, Object> variables = Map.of("v", List.of(List.of(List.of(List.of(1)))));
// when
Outcome outcome = intercept("{ _health }", variables, Map.of());
// then
assertThat(outcome)
.extracting(Outcome::executed, Outcome::code)
.containsExactly(false, "REQUEST_ERROR");
}
@Test
void anUnregisteredExtensionKeyIsRejected() {
// given
Map<String, Object> extensions = Map.of("idempotencyKey", "request-1");
// when
Outcome outcome = intercept("{ _health }", Map.of(), extensions);
// then
assertThat(outcome)
.extracting(Outcome::executed, Outcome::code)
.containsExactly(false, "REQUEST_ERROR");
}
private Outcome intercept(
String document, Map<String, Object> variables, Map<String, Object> extensions) {
AtomicBoolean executed = new AtomicBoolean();
Outcome[] outcome = new Outcome[1];
runner.run(
context -> {
WebGraphQlInterceptor interceptor = context.getBean(GraphQlPlatformWebInterceptor.class);
WebGraphQlResponse response =
interceptor
.intercept(
request(document, variables, extensions),
next -> {
executed.set(true);
return Mono.empty();
})
.block();
List<ResponseError> errors = response == null ? List.of() : response.getErrors();
ResponseError error = errors.isEmpty() ? null : errors.get(0);
outcome[0] =
new Outcome(
executed.get(),
error == null ? null : String.valueOf(error.getExtensions().get("code")));
});
return outcome[0];
}
private static WebGraphQlRequest request(
String document, Map<String, Object> variables, Map<String, Object> extensions) {
return new WebGraphQlRequest(
URI.create("http://localhost/graphql"),
new HttpHeaders(),
new LinkedMultiValueMap<>(),
null,
Map.of(),
Map.of("query", document, "variables", variables, "extensions", extensions),
"request-1",
Locale.ROOT);
}
private record Outcome(boolean executed, String code) {}
}
@@ -1,8 +1,6 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import java.time.Clock;
import java.util.Set;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
@@ -29,23 +27,16 @@ import org.springframework.context.annotation.Configuration;
public class CallbackRequestConfiguration {
/**
* Resolves the URL a provider actually called.
* Resolves the URL a provider actually called, from what the container reports. Forwarded headers
* are trusted by the container alone ({@code server.forward-headers-strategy=native} and {@code
* server.tomcat.remoteip.internal-proxies}); this bean has no proxy list of its own.
*
* <p>The trusted-proxy set is empty by default, and that default is the safe one rather than the
* convenient one: with no entry, forwarded headers are never honoured and the resolver uses what
* the container observed. Honouring them unconditionally would let any caller choose the URL that
* gets signature-verified, which defeats the signature. A deployment behind a load balancer names
* its proxies explicitly.
*
* @param trustedProxies peers whose forwarded headers may be believed
* @return the resolver
*/
@Bean
@ConditionalOnMissingBean(ExternalRequestUrlResolver.class)
public ExternalRequestUrlResolver externalRequestUrlResolver(
@Value("${ca-skeleton.notification.platform.callbacks.trusted-proxies:}")
Set<String> trustedProxies) {
return new ExternalRequestUrlResolver(trustedProxies);
public ExternalRequestUrlResolver externalRequestUrlResolver() {
return new ExternalRequestUrlResolver();
}
/**
@@ -1,59 +1,28 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
/**
* Reconstructs the URL the provider actually called.
*
* <p>Several providers sign the request URL, so getting this wrong turns every valid webhook into a
* signature failure. Forwarded headers are only honoured when the immediate peer is a configured
* trusted proxy: trusting them unconditionally would let any caller choose the URL that gets
* verified, which defeats the signature entirely.
* signature failure. The URL is built only from what the container reports — {@code getScheme},
* {@code getServerName}, {@code getServerPort}. Behind a proxy that is correct exactly when {@code
* server.forward-headers-strategy=native}: Tomcat's {@code RemoteIpValve} then applies {@code
* X-Forwarded-*} from the peers in {@code server.tomcat.remoteip.internal-proxies} and from nobody
* else. This class used to parse {@code Forwarded}/{@code X-Forwarded-*} itself against its own
* trusted-proxy list, which was a second trust decision that could disagree with the container's.
*/
public final class ExternalRequestUrlResolver {
private final Set<String> trustedProxies;
public ExternalRequestUrlResolver(Set<String> trustedProxies) {
this.trustedProxies = Set.copyOf(Objects.requireNonNull(trustedProxies, "trustedProxies"));
}
/** External URL of a request. */
/** External URL of a request, as the container sees it. */
public String resolve(HttpServletRequest request) {
Objects.requireNonNull(request, "request");
String scheme = request.getScheme();
String host = request.getServerName();
int port = request.getServerPort();
if (trustedProxies.contains(request.getRemoteAddr())) {
String forwarded = request.getHeader("Forwarded");
if (forwarded != null) {
for (String element : forwarded.split(";", -1)) {
String trimmed = element.trim().toLowerCase(Locale.ROOT);
if (trimmed.startsWith("proto=")) {
scheme = trimmed.substring("proto=".length());
} else if (trimmed.startsWith("host=")) {
host = element.trim().substring("host=".length());
port = -1;
}
}
} else {
String protoHeader = request.getHeader("X-Forwarded-Proto");
String hostHeader = request.getHeader("X-Forwarded-Host");
if (protoHeader != null) {
scheme = protoHeader;
}
if (hostHeader != null) {
host = hostHeader;
port = -1;
}
}
}
StringBuilder url = new StringBuilder(scheme).append("://").append(host);
StringBuilder url = new StringBuilder(scheme).append("://").append(request.getServerName());
boolean defaultPort =
port < 0
|| ("https".equalsIgnoreCase(scheme) && port == 443)
@@ -45,9 +45,6 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/notifications")
public class NotificationSubmissionController {
/** What a caller gets when it names no version; the first published version of a template. */
private static final long DEFAULT_TEMPLATE_VERSION = 1L;
private final AcceptNotificationUseCase accept;
/**
@@ -76,9 +73,8 @@ public class NotificationSubmissionController {
channel(request.channel()),
request.address(),
request.template(),
request.templateVersion() == null
? DEFAULT_TEMPLATE_VERSION
: request.templateVersion(),
// An omitted version or locale stays omitted: the use case owns both defaults.
Optional.ofNullable(request.templateVersion()),
locale(request.locale()),
NotificationVariableCoercion.coerceAll(request.variables()),
Optional.ofNullable(request.idempotencyKey()).filter(key -> !key.isBlank()),
@@ -109,20 +105,20 @@ public class NotificationSubmissionController {
}
/**
* The locale a caller named, or the platform default.
* The locale a caller named, or none.
*
* <p>{@link Locale#forLanguageTag} answers {@code Locale.ROOT} for anything it cannot parse
* rather than failing, so an unparseable tag is refused explicitly — silently rendering a Korean
* notification in the root locale is the kind of wrong that reaches a recipient.
*/
private static Locale locale(String tag) {
private static Optional<Locale> locale(String tag) {
if (tag == null || tag.isBlank()) {
return Locale.getDefault();
return Optional.empty();
}
Locale parsed = Locale.forLanguageTag(tag.trim());
if (parsed.equals(Locale.ROOT)) {
throw new IllegalArgumentException("locale must be a BCP 47 language tag");
}
return parsed;
return Optional.of(parsed);
}
}
@@ -72,7 +72,7 @@ public class NotificationTemplateController {
PublishNotificationTemplateCommand command =
new PublishNotificationTemplateCommand(
request.templateId(),
request.version() == null ? 1L : request.version(),
Optional.ofNullable(request.version()),
channel(request.channel()),
locale(request.locale()),
Optional.ofNullable(request.fallbackLocale())
@@ -50,16 +50,6 @@ class CallbackRequestConfigurationTest {
.doesNotHaveBean(CallbackRequestFactory.class));
}
@Test
@DisplayName("no trusted proxy is configured by default")
void noTrustedProxyByDefault() {
// The safe default rather than the convenient one: with no entry, a forwarded header cannot
// choose the URL that gets signature-verified.
runner
.withPropertyValues("ca-skeleton.notification.platform.callbacks.enabled=true")
.run(context -> assertThat(context).hasSingleBean(ExternalRequestUrlResolver.class));
}
@Configuration(proxyBeanMethods = false)
static class ClockConfiguration {
@Bean
@@ -0,0 +1,56 @@
package dev.caskeleton.adapter.inbound.web.notification.platform.callback;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* The URL a callback signature is verified against is the one the container reports.
*
* <p>Forwarded headers are the container's business: with {@code
* server.forward-headers-strategy=native}, Tomcat's {@code RemoteIpValve} rewrites scheme, host and
* port from trusted proxies only. A second parser here was a second trust decision that could
* disagree with the first.
*/
class ExternalRequestUrlResolverTest {
private final ExternalRequestUrlResolver resolver = new ExternalRequestUrlResolver();
@Test
void forwardedHeadersOnTheRequestDoNotChangeTheResolvedUrl() {
// given
MockHttpServletRequest request = request("http", "internal.local", 8080);
request.setRemoteAddr("10.0.0.5");
request.addHeader("Forwarded", "proto=https;host=attacker.example");
request.addHeader("X-Forwarded-Proto", "https");
request.addHeader("X-Forwarded-Host", "attacker.example");
// when
String url = resolver.resolve(request);
// then
assertThat(url).isEqualTo("http://internal.local:8080/callbacks/ses?a=1");
}
@Test
void theContainersSchemeAndHostAreUsedAndADefaultPortIsOmitted() {
// given
MockHttpServletRequest request = request("https", "hooks.example.com", 443);
// when
String url = resolver.resolve(request);
// then
assertThat(url).isEqualTo("https://hooks.example.com/callbacks/ses?a=1");
}
private static MockHttpServletRequest request(String scheme, String host, int port) {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/callbacks/ses");
request.setScheme(scheme);
request.setServerName(host);
request.setServerPort(port);
request.setQueryString("a=1");
return request;
}
}
@@ -13,7 +13,6 @@ import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -29,7 +28,6 @@ class NotificationCallbackMvcControllerTest {
private static final Clock CLOCK =
Clock.fixed(Instant.parse("2026-08-14T00:00:00Z"), ZoneOffset.UTC);
private static final String TRUSTED_PROXY = "10.0.0.1";
private final List<ProviderCallbackHttpRequest> received = new ArrayList<>();
@@ -45,7 +43,7 @@ class NotificationCallbackMvcControllerTest {
private final NotificationCallbackMvcController controller =
new NotificationCallbackMvcController(
rejectingIngress,
new CallbackRequestFactory(new ExternalRequestUrlResolver(Set.of(TRUSTED_PROXY)), CLOCK),
new CallbackRequestFactory(new ExternalRequestUrlResolver(), CLOCK),
NotificationCallbackMvcController.MAX_STORABLE_BODY_BYTES);
@Test
@@ -66,7 +64,7 @@ class NotificationCallbackMvcControllerTest {
}
@Test
void aForwardedHostFromAnUntrustedPeerIsIgnored() {
void aForwardedHostHeaderIsIgnored() {
var request = request("application/json", "{}".getBytes(StandardCharsets.UTF_8));
request.setRemoteAddr("203.0.113.9");
request.addHeader("X-Forwarded-Proto", "https");
@@ -79,11 +77,13 @@ class NotificationCallbackMvcControllerTest {
}
@Test
void aForwardedHostFromATrustedProxyBecomesTheCanonicalUrl() {
void theSchemeAndHostTheContainerReportsBecomeTheCanonicalUrl() {
// RemoteIpValve (server.forward-headers-strategy=native) has already applied a trusted
// proxy's X-Forwarded-* to these values before the controller runs.
var request = request("application/json", "{}".getBytes(StandardCharsets.UTF_8));
request.setRemoteAddr(TRUSTED_PROXY);
request.addHeader("X-Forwarded-Proto", "https");
request.addHeader("X-Forwarded-Host", "callback.example.com");
request.setScheme("https");
request.setServerName("callback.example.com");
request.setServerPort(443);
assertThatThrownBy(() -> controller.callback("twilio", "twilio-primary", request))
.isInstanceOf(CallbackValidationException.class);
+4 -2
View File
@@ -23,8 +23,10 @@ Package root: `dev.caskeleton.adapter.inbound.web`.
leaking Swagger dependencies into `shared-contract`.
Every service ships this leaf, so it holds only what the servlet production path reaches: its
`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the beans and binds the
settings; `app-bootstrap` no longer scans this leaf), and the types
`AutoConfiguration.imports` roots (`WebAdapterAutoConfiguration` imports the envelope, filters,
health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chain, method security
and permission port, so an application with its own posture excludes only that root; nobody scans
this leaf), and the types
`app-bootstrap`, `sample-portfolio`, `web-fileserver` and `composition:fileserver-platform` name —
plus their transitive references. Library code that no production path reaches (streaming, virtual
threads, patch, codecs, OpenAPI 3.2, URI/method policy, versioning, operation, budget, contract,
@@ -1,13 +1,5 @@
package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
import dev.caskeleton.adapter.inbound.web.auth.JwtDecoderConfig;
import dev.caskeleton.adapter.inbound.web.auth.JwtToAuthenticatedPrincipalConverter;
import dev.caskeleton.adapter.inbound.web.auth.RedisSessionWebConfig;
import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import dev.caskeleton.adapter.inbound.web.config.JacksonNullableConfig;
import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig;
import dev.caskeleton.adapter.inbound.web.config.PresentationWebConfig;
@@ -19,9 +11,7 @@ import dev.caskeleton.adapter.inbound.web.filter.RequestLoggingFilter;
import dev.caskeleton.adapter.inbound.web.observability.MdcCorrelationIdPortAdapter;
import dev.caskeleton.adapter.inbound.web.ratelimit.EdgeRateLimitTransportSettings;
import dev.caskeleton.adapter.inbound.web.ratelimit.RateLimitWebConfig;
import dev.caskeleton.adapter.inbound.web.settings.CorsSettings;
import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -29,36 +19,26 @@ import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
/**
* The HTTP adapter this leaf ships: security, error envelope, filters, health endpoint and their
* settings.
* The HTTP adapter this leaf ships, minus its security posture: error envelope, filters, health
* endpoint, rate limiting and their settings. The JWT security chain and method security are {@link
* WebSecurityAutoConfiguration}, a separate root an application can exclude on its own.
*
* <p>These used to be found by the composition root's component scan of the whole {@code
* dev.caskeleton} tree. Registering them here means an application gets them from this module being
* on its classpath, and its own scan never has to reach into adapter packages.
*
* <p>First among auto-configurations, which is where a scanned user configuration used to sit: the
* security filter chain and JWT decoder have to be defined before Spring Boot's own security
* auto-configurations decide whether to back off, and {@link GlobalExceptionHandler} before {@link
* WebMvcPlatformAutoConfiguration} offers its default.
* <p>First among auto-configurations, which is where a scanned user configuration used to sit:
* {@link GlobalExceptionHandler} has to be defined before {@link WebMvcPlatformAutoConfiguration}
* offers its default.
*/
@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@EnableConfigurationProperties({
CorsSettings.class,
EdgeRateLimitTransportSettings.class,
PresentationSettings.class,
RolePermissionPolicy.class,
SecuritySettings.class,
WebMvcPlatformSettings.class
})
@Import({
JwtDecoderConfig.class,
JwtToAuthenticatedPrincipalConverter.class,
RedisSessionWebConfig.class,
SecurityConfig.class,
AuthorizationAdapter.class,
MethodSecurityConfig.class,
RolePermissionRegistry.class,
JacksonNullableConfig.class,
OpenApiContractConfig.class,
PresentationWebConfig.class,
@@ -0,0 +1,50 @@
package dev.caskeleton.adapter.inbound.web.mvc.autoconfigure;
import dev.caskeleton.adapter.inbound.web.auth.JwtDecoderConfig;
import dev.caskeleton.adapter.inbound.web.auth.JwtToAuthenticatedPrincipalConverter;
import dev.caskeleton.adapter.inbound.web.auth.RedisSessionWebConfig;
import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.AuthorizationAdapter;
import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionPolicy;
import dev.caskeleton.adapter.inbound.web.authz.RolePermissionRegistry;
import dev.caskeleton.adapter.inbound.web.settings.CorsSettings;
import dev.caskeleton.adapter.inbound.web.settings.SecuritySettings;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.core.Ordered;
/**
* The production security posture this leaf ships: the JWT security filter chain, method security,
* the role-to-permission authorization port and their settings.
*
* <p>Separate from {@link WebAdapterAutoConfiguration} so an application that brings its own
* posture — the public demo sample, a contract fixture — excludes exactly this class and still gets
* the error envelope, filters, health endpoint and rate limiting from the web root. Before the
* split the only way to drop the security chain was to drop the whole root and component-scan the
* leaf back in minus two classes, and every new controller in the leaf then arrived in that scan
* whether it was meant to or not.
*
* <p>First among auto-configurations for the same reason as the web root: the filter chain and the
* JWT decoder have to exist before Spring Boot's own security auto-configurations decide whether to
* back off.
*/
@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@EnableConfigurationProperties({
CorsSettings.class,
RolePermissionPolicy.class,
SecuritySettings.class
})
@Import({
JwtDecoderConfig.class,
JwtToAuthenticatedPrincipalConverter.class,
RedisSessionWebConfig.class,
SecurityConfig.class,
AuthorizationAdapter.class,
MethodSecurityConfig.class,
RolePermissionRegistry.class
})
public class WebSecurityAutoConfiguration {}
@@ -79,7 +79,7 @@ public class DurableOperationController {
@AuthenticationPrincipal AuthenticatedPrincipal principal) {
String payload = request.payload().toString();
OperationAcceptance acceptance =
submit.submit(
submit.handle(
new OperationCommand(
new DurableOperationId(UUID.randomUUID().toString()),
request.operationName(),
@@ -17,37 +17,22 @@ import org.springframework.web.servlet.HandlerInterceptor;
import tools.jackson.databind.ObjectMapper;
/**
* Maps provider-neutral rate-limit outcomes to the stable HTTP signaling contract.
*
* <p>Disabled instances have no bridge and therefore cannot resolve a subject, pseudonymize, or
* invoke a provider.
* Maps provider-neutral rate-limit outcomes to the stable HTTP signaling contract. It exists only
* when rate limiting is enabled; a disabled edge registers no interceptor at all.
*/
public final class RateLimitInterceptor implements HandlerInterceptor {
private final EdgeRateLimitTransportBridge bridge;
private final ObjectMapper objectMapper;
private RateLimitInterceptor(EdgeRateLimitTransportBridge bridge, ObjectMapper objectMapper) {
this.bridge = bridge;
public RateLimitInterceptor(EdgeRateLimitTransportBridge bridge, ObjectMapper objectMapper) {
this.bridge = Objects.requireNonNull(bridge, "bridge must not be null");
this.objectMapper = Objects.requireNonNull(objectMapper, "objectMapper must not be null");
}
public static RateLimitInterceptor enabled(
EdgeRateLimitTransportBridge bridge, ObjectMapper objectMapper) {
return new RateLimitInterceptor(
Objects.requireNonNull(bridge, "bridge must not be null"), objectMapper);
}
public static RateLimitInterceptor disabled(ObjectMapper objectMapper) {
return new RateLimitInterceptor(null, objectMapper);
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (bridge == null) {
return true;
}
return switch (bridge.evaluate(request)) {
case RateLimitOutcome.Evaluated evaluated -> handleEvaluated(response, evaluated.decision());
case RateLimitOutcome.Unavailable unavailable ->
@@ -54,7 +54,7 @@ public class RateLimitWebConfig implements WebMvcConfigurer {
transportSettings.defaultPolicyId(),
transportSettings.callerDeadlineBudget(),
SecureRandomRateLimitEvaluationIdGenerator.versionOne());
this.rateLimitInterceptor = RateLimitInterceptor.enabled(bridge, objectMapper);
this.rateLimitInterceptor = new RateLimitInterceptor(bridge, objectMapper);
}
@Override
@@ -1,2 +1,3 @@
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration
dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration
@@ -36,6 +36,7 @@ class WebAutoConfigurationRegistrationTest {
private static final List<String> PUBLISHED_ROOTS =
List.of(
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration");
@Test
@@ -3,8 +3,6 @@ package dev.caskeleton.adapter.inbound.web.ratelimit;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort;
import dev.caskeleton.shared.ratelimit.EdgeSubjectPseudonymizer;
import dev.caskeleton.shared.ratelimit.RateLimitDecision;
import dev.caskeleton.shared.ratelimit.RateLimitOutcome;
import dev.caskeleton.shared.ratelimit.RateLimitSubjectDigest;
@@ -12,7 +10,6 @@ import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
@@ -105,38 +102,6 @@ class RateLimitInterceptorTest {
.contains("\"retryable\":false");
}
@Test
void disabledModeHasNoProviderOrPseudonymizerSideEffects() throws Exception {
AtomicInteger calls = new AtomicInteger();
EdgeRateLimitPort port =
request -> {
calls.incrementAndGet();
throw new AssertionError("disabled interceptor must not call the provider");
};
EdgeSubjectPseudonymizer pseudonymizer =
subject -> {
calls.incrementAndGet();
throw new AssertionError("disabled interceptor must not pseudonymize");
};
EdgeRateLimitTransportBridge unusedBridge =
new EdgeRateLimitTransportBridge(
port,
pseudonymizer,
new RateLimitKeyResolver(),
CLOCK,
"api-default",
Duration.ofSeconds(1),
() -> "ev1:" + "D".repeat(22));
MockHttpServletResponse response = new MockHttpServletResponse();
boolean proceed =
RateLimitInterceptor.disabled(objectMapper).preHandle(request(), response, unusedBridge);
assertThat(proceed).isTrue();
assertThat(calls).hasValue(0);
assertThat(response.getHeader(ApiHeaders.X_RATELIMIT_LIMIT)).isNull();
}
private RateLimitInterceptor interceptor(RateLimitOutcome outcome) {
EdgeRateLimitTransportBridge bridge =
new EdgeRateLimitTransportBridge(
@@ -147,7 +112,7 @@ class RateLimitInterceptorTest {
"api-default",
Duration.ofSeconds(1),
() -> "ev1:" + "D".repeat(22));
return RateLimitInterceptor.enabled(bridge, objectMapper);
return new RateLimitInterceptor(bridge, objectMapper);
}
private MockHttpServletRequest request() {
@@ -1,6 +1,7 @@
package dev.caskeleton.webtestkit;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.testkit.fault.FaultFixtureController;
import dev.caskeleton.adapter.inbound.web.testkit.mvc.ContractFixtureController;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -24,10 +25,11 @@ import org.springframework.security.web.SecurityFilterChain;
* includes this leaf's {@code WebMvcPlatformAutoConfiguration}, so errors are answered by the
* production {@code GlobalExceptionHandler} as an {@code Envelope}, exactly as a deployment would.
*
* <p>The one entry left out is this leaf's own {@link WebAdapterAutoConfiguration}: it is the whole
* adapter — the production security chain, its JWT settings, the request-logging filter and the
* composition-root pseudonymizer that filter needs — which is the "sum of the leaf" the paragraph
* above keeps out. Excluded by class, so a rename breaks compilation rather than the gate.
* <p>The two entries left out are this leaf's own roots: {@link WebSecurityAutoConfiguration} (the
* production security chain and its JWT settings) and {@link WebAdapterAutoConfiguration} (the
* request-logging filter and the composition-root pseudonymizer that filter needs). Together they
* are the "sum of the leaf" the paragraph above keeps out. Excluded by class, so a rename breaks
* compilation rather than the gate.
*/
// Outside `dev.caskeleton.adapter.inbound.web`, which the composition root component-scans.
// A fixture application under that root is loaded into the real deployment: its permit-all
@@ -35,7 +37,8 @@ import org.springframework.security.web.SecurityFilterChain;
// filter chain. @TestConfiguration would exclude it from scanning but is not accepted by
// @SpringBootTest(classes = ...), so the package is what keeps it out.
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class)
@EnableAutoConfiguration(
exclude = {WebAdapterAutoConfiguration.class, WebSecurityAutoConfiguration.class})
@Import({ContractFixtureController.class, FaultFixtureController.class})
public class ContractFixtureApplication {
@@ -1,6 +1,7 @@
package dev.caskeleton.webtestkit;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.testkit.order.PipelineOrderFixtureController;
import dev.caskeleton.adapter.inbound.web.testkit.order.WebPipelineRecorder;
import dev.caskeleton.adapter.inbound.web.testkit.order.WebPipelineStage;
@@ -41,13 +42,15 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
// filter chain. @TestConfiguration would exclude it from scanning but is not accepted by
// @SpringBootTest(classes = ...), so the package is what keeps it out.
@Configuration(proxyBeanMethods = false)
// Not the adapter's own root: its security chain and filters would be stages this fixture did not
// Not the adapter's own roots: their security chain and filters would be stages this fixture did
// not
// declare, and the recorded order would be about them rather than the semantic pipeline. So this
// fixture proves the semantic order and the async single-observation, not where the real filters
// sit: the registered order of the request-id filter against springSecurityFilterChain is asserted
// on the real auto-configuration by app-bootstrap's OperationalContractRuntimeTest, and the
// consequence (a 401 envelope carrying the assigned request id) by SecurityModeWebContractTest.
@EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class)
@EnableAutoConfiguration(
exclude = {WebAdapterAutoConfiguration.class, WebSecurityAutoConfiguration.class})
@Import(PipelineOrderFixtureController.class)
public class PipelineOrderFixtureApplication implements WebMvcConfigurer {
+4 -2
View File
@@ -62,7 +62,7 @@ values matter only in a composition that adopts it.
| `app.websocket.endpoint` | `APP_WEBSOCKET_ENDPOINT` | `/ws` |
| `app.websocket.allowed-origins` | `APP_WEBSOCKET_ALLOWED_ORIGINS` | `http://localhost:3000`; explicit origins only |
| `app.websocket.broadcast-destination` | `APP_WEBSOCKET_BROADCAST_DESTINATION` | `/topic/events` |
| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`; messages each STOMP client channel (inbound, outbound) queues before rejecting |
| `app.websocket.channel-queue-capacity` | `APP_WEBSOCKET_CHANNEL_QUEUE_CAPACITY` | `10000`; messages each STOMP channel (client inbound, client outbound, broker) queues before rejecting |
`WebSocketSettings` is `@Validated`. Invalid enabled settings fail context startup.
@@ -101,7 +101,9 @@ WebSocket is a **build-composition opt-in**, not a dormant feature inside the de
A future feature may contribute a `LiveEventProjector<T>` bean for one exact `@DomainEvent` class.
The broadcaster sends only when exactly one projector matches. Zero or duplicate projectors,
projection failures, invalid event types, null fields, and over-limit maps are dropped. The wire
envelope contains only `type`, bounded string `fields`, and `occurredAt`.
envelope contains only `type`, bounded string `fields`, and `occurredAt`. The broker channel has its
own bounded executor, so the simple broker's fan-out to subscribers never runs on the thread that
published the domain event; a full broker queue drops the event (best-effort, R1).
No current `sample-portfolio` feature publishes a WebSocket event or contributes a projector.
@@ -78,7 +78,8 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* Spring's channel executor defaults to an {@code Integer.MAX_VALUE} queue and pool, so a slow
* consumer grows the heap without limit. Here the pool keeps Spring's core size and the queue is
* {@code app.websocket.channel-queue-capacity}; a full queue rejects the message instead.
* {@code app.websocket.channel-queue-capacity}; a full queue rejects the message instead. Used
* for the client inbound, client outbound and broker channels.
*/
private ChannelRegistration bounded(ChannelRegistration registration) {
registration
@@ -89,8 +90,16 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
return registration;
}
/**
* The broker channel gets the same bounded executor as the client channels. Without one it is a
* synchronous channel, so {@link LiveEventStompBroadcaster}'s {@code convertAndSend} ran the
* simple broker's fan-out to every subscriber on the thread that published the domain event — the
* use case's own thread. Live push is best-effort (R1): a full queue rejects the message and the
* broadcaster drops it, rather than slowing the publisher down by the subscriber count.
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
bounded(registry.configureBrokerChannel());
registry.enableSimpleBroker("/topic");
registry.setApplicationDestinationPrefixes("/app");
}
@@ -10,6 +10,7 @@ import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/** The STOMP channel reaches an application through this module's own auto-configuration entry. */
@@ -61,6 +62,27 @@ class WebSocketAutoConfigurationTest {
});
}
@Test
void brokerChannelFansOutOnItsOwnBoundedExecutorInsteadOfThePublishingThread() {
// given
WebApplicationContextRunner configured =
runner.withPropertyValues("app.websocket.channel-queue-capacity=64");
// when
configured.run(
context -> {
// then
assertThat(context.getBean("brokerChannel", ExecutorSubscribableChannel.class))
.extracting(ExecutorSubscribableChannel::getExecutor)
.isInstanceOfSatisfying(
ThreadPoolTaskExecutor.class,
executor ->
assertThat(executor.getQueueCapacity())
.as("broker channel queue capacity")
.isEqualTo(64));
});
}
@Test
void switchedOffHoldsNothing() {
runner
@@ -5,7 +5,7 @@ import static org.mockito.Mockito.mock;
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration;
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
import dev.caskeleton.adapter.outbound.support.startup.RequiredAdapterDisabledException;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.application.cache.CacheRegionPort;
import dev.caskeleton.application.idempotency.IdempotencyStorePort;
import dev.caskeleton.application.lease.DistributedLeasePort;
@@ -161,7 +161,7 @@ class RedisCapabilityCompositionTest {
.run(
context ->
assertThat(context.getStartupFailure())
.hasRootCauseInstanceOf(RequiredAdapterDisabledException.class)
.hasRootCauseInstanceOf(StartupFailureException.class)
.hasStackTraceContaining("ca-skeleton.capabilities.idempotency.key-version=2")
.hasStackTraceContaining("unsupported without dual-read"));
}
@@ -545,7 +545,7 @@ holder 가 락을 잡을 수 있다.
실패시키는 일이 애플리케이션이 readiness 를 보고하기 *전에* 일어난다는 뜻이다. 따라서 절반만
마이그레이션된 스키마가 트래픽을 받는 일이 구조적으로 없다(actuator readiness probe 의 형태
자체는 health-lifecycle 브랜치가 소유하고, 여기서는 "마이그레이션 → ready" 순서만 책임진다).
- **`FlywayException`을 `MigrationFailedException`(exit 70)으로 번역한다.** 일반적이고 구분 안 되는
- **`FlywayException`을 `StartupFailures.migrationFailed`(`MIGRATION_FAILED`, exit 70)로 번역한다.** 일반적이고 구분 안 되는
스택트레이스 대신 구조화된 `MIGRATION_FAILED` 로그와 표준 exit 코드를 남기기 위함이다.
- **멀티 인스턴스에서는 in-app 마이그레이션 + Flyway 자체 schema-history 락에 의존하는 것이 기본
전략이다.** 여러 레플리카의 동시 `migrate()`를 Flyway 의 락이 직렬화한다. 대안인 "in-app
@@ -40,8 +40,9 @@ final class JpaDangerousConfigurationGuard {
/**
* Validates the resolved environment.
*
* @throws dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException naming the
* unsafe property, its environment key and the approved alternatives
* @throws dev.caskeleton.adapter.outbound.support.startup.StartupFailureException
* (PROFILE_MISMATCH) naming the unsafe property, its environment key and the approved
* alternatives
*/
public void validate(Environment environment) {
Objects.requireNonNull(environment, "environment");
@@ -2,7 +2,7 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
import static net.logstash.logback.argument.StructuredArguments.kv;
import dev.caskeleton.adapter.outbound.support.startup.MigrationFailedException;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import dev.caskeleton.adapter.outbound.support.startup.StartupPhase;
import org.flywaydb.core.Flyway;
@@ -14,8 +14,8 @@ import org.springframework.boot.flyway.autoconfigure.FlywayMigrationStrategy;
/**
* Runs the Flyway migration during context refresh so it completes before readiness, and translates
* a {@link FlywayException} into a {@link MigrationFailedException} (exit 70). See README for the
* design rationale.
* a {@link FlywayException} into a {@link StartupFailureException} with {@code MIGRATION_FAILED}
* (exit 70). See README for the design rationale.
*/
class MigrationStartupRunner implements FlywayMigrationStrategy {
@@ -95,11 +95,11 @@ class DurableOperationSubmissionOutboxIntegrationTest {
void retryUnderTheSameOperationIdLeavesThePublishedOutboxRowAlone() throws SQLException {
// given
SubmitDurableOperationUseCase useCase = context.getBean(SubmitDurableOperationUseCase.class);
useCase.submit(command());
useCase.handle(command());
execute("UPDATE outbox_event SET status = 'PUBLISHED'");
// when
OperationAcceptance retry = useCase.submit(command());
OperationAcceptance retry = useCase.handle(command());
// then
assertThat(List.of(retry.alreadyAccepted(), outboxStatuses()))
@@ -111,14 +111,14 @@ class DurableOperationSubmissionOutboxIntegrationTest {
throws SQLException {
// given
SubmitDurableOperationUseCase useCase = context.getBean(SubmitDurableOperationUseCase.class);
useCase.submit(command());
useCase.handle(command());
execute("UPDATE outbox_event SET status = 'PUBLISHED'");
// With the operation row gone the next submission is a creation again, so it appends an outbox
// event under the event id that is already there.
execute("DELETE FROM durable_operation");
// when
Throwable thrown = catchThrowable(() -> useCase.submit(command()));
Throwable thrown = catchThrowable(() -> useCase.handle(command()));
// then
// SpringTransactionPort classifies the commit failure; 23505 is the primary key.
@@ -7,8 +7,7 @@ import dev.caskeleton.application.lock.DistributedLockPort;
import dev.caskeleton.application.outbox.OutboxStorePort;
import dev.caskeleton.application.transaction.TransactionPort;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.DomainContextPropagatorFactory;
import dev.caskeleton.shared.concurrency.DomainContextStrategy;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import jakarta.persistence.EntityManagerFactory;
import java.io.IOException;
import java.time.Clock;
@@ -191,7 +190,7 @@ class PersistenceJpaCapabilityAssemblyTest {
@Bean
DomainContextPropagator domainContextPropagator() {
return DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL);
return new ThreadLocalDomainContextPropagator();
}
}
@@ -2,7 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException;
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.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -42,8 +43,8 @@ class FlywayProdSafetyValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).hasStackTraceContaining("out-of-order");
ProfileMismatchException ex = profileFailure(context);
assertThat(ex.getExitCode()).isEqualTo(71);
StartupFailureException ex = profileFailure(context);
assertThat(ex.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH);
});
}
@@ -93,13 +94,16 @@ class FlywayProdSafetyValidatorTest {
.run(context -> assertThat(context).hasNotFailed());
}
private static ProfileMismatchException profileFailure(AssertableApplicationContext context) {
private static StartupFailureException profileFailure(AssertableApplicationContext context) {
Throwable t = context.getStartupFailure();
while (t != null && !(t instanceof ProfileMismatchException)) {
while (t != null && !(t instanceof StartupFailureException)) {
t = t.getCause();
}
assertThat(t).isInstanceOf(ProfileMismatchException.class);
return (ProfileMismatchException) t;
assertThat(t)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH));
return (StartupFailureException) t;
}
@Configuration
@@ -2,7 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException;
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.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
@@ -29,7 +30,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_DATASOURCE_POOL_MAX_SIZE")
.hasStackTraceContaining(">= 1");
});
@@ -55,7 +60,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("connection-timeout")
// names the operator-facing env key, not just the Spring property
.hasStackTraceContaining("APP_DATASOURCE_CONNECTION_TIMEOUT")
@@ -83,7 +92,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("validation-timeout")
.hasStackTraceContaining("connection-timeout");
});
@@ -101,7 +114,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("keepalive-time")
.hasStackTraceContaining("max-lifetime");
});
@@ -118,7 +135,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("keepalive-time")
.hasStackTraceContaining("max-lifetime");
});
@@ -134,7 +155,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("leak-detection-threshold")
.hasStackTraceContaining("2000");
});
@@ -179,7 +204,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("connection-timeout")
.hasStackTraceContaining(">= 250");
});
@@ -204,7 +233,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("validation-timeout")
.hasStackTraceContaining("connection-timeout");
});
@@ -218,7 +251,11 @@ class HikariPoolConstraintValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("connection-timeout")
.hasStackTraceContaining("valid duration");
});
@@ -4,7 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -38,7 +39,9 @@ class JpaDangerousConfigurationGuardTest {
// then
assertThat(thrown)
.isInstanceOf(ProfileMismatchException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH))
.hasMessageContaining("APP_DATASOURCE_DDL_AUTO")
.hasMessageContaining("Flyway owns schema change");
}
@@ -55,7 +58,9 @@ class JpaDangerousConfigurationGuardTest {
// then
assertThat(thrown)
.isInstanceOf(ProfileMismatchException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH))
.hasMessageContaining("APP_DATASOURCE_DDL_AUTO");
}
@@ -70,7 +75,10 @@ class JpaDangerousConfigurationGuardTest {
Throwable thrown = catchThrowable(() -> guard.validate(production));
// then
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH));
}
@Test
@@ -84,7 +92,10 @@ class JpaDangerousConfigurationGuardTest {
Throwable thrown = catchThrowable(() -> guard.validate(staging));
// then
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH));
}
@ParameterizedTest
@@ -112,7 +123,10 @@ class JpaDangerousConfigurationGuardTest {
Throwable thrown = catchThrowable(() -> guard.validate(mixed));
// then
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH));
}
@Test
@@ -126,7 +140,10 @@ class JpaDangerousConfigurationGuardTest {
Throwable thrown = catchThrowable(() -> guard.validate(none));
// then
assertThat(thrown).isInstanceOf(ProfileMismatchException.class);
assertThat(thrown)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH));
}
@ParameterizedTest
@@ -11,7 +11,8 @@ import static org.mockito.Mockito.when;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.adapter.outbound.support.startup.MigrationFailedException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.flywaydb.core.Flyway;
@@ -69,9 +70,11 @@ class MigrationStartupRunnerTest {
when(flyway.migrate()).thenThrow(root);
assertThatThrownBy(() -> runner.migrate(flyway))
.isInstanceOf(MigrationFailedException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.MIGRATION_FAILED))
.hasCause(root)
.satisfies(ex -> assertThat(((MigrationFailedException) ex).getExitCode()).isEqualTo(70));
.satisfies(ex -> assertThat(((StartupFailureException) ex).getExitCode()).isEqualTo(70));
}
@Test
@@ -87,7 +90,10 @@ class MigrationStartupRunnerTest {
Flyway flyway = mock(Flyway.class);
when(flyway.migrate()).thenThrow(new FlywayException("boom"));
assertThatThrownBy(() -> runner.migrate(flyway)).isInstanceOf(MigrationFailedException.class);
assertThatThrownBy(() -> runner.migrate(flyway))
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.MIGRATION_FAILED));
String args =
appender.list.stream()
@@ -2,7 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException;
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.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
@@ -28,7 +29,11 @@ class OpenInViewSafetyValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_DATASOURCE_OPEN_IN_VIEW")
.hasStackTraceContaining("must be false");
});
@@ -41,7 +46,11 @@ class OpenInViewSafetyValidatorTest {
.run(
context ->
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("must be false"));
}
@@ -2,7 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.jupiter.api.Test;
@@ -33,7 +34,9 @@ class PersistenceVendorProdSafetyValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(ProfileMismatchException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH))
.hasStackTraceContaining(PersistenceVendorProdSafetyValidator.VENDOR_KEY);
});
}
@@ -49,7 +52,9 @@ class PersistenceVendorProdSafetyValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(ProfileMismatchException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH))
.hasStackTraceContaining(PersistenceVendorProdSafetyValidator.JDBC_URL_ENV_KEY);
});
}
@@ -2,7 +2,8 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.junit.jupiter.api.Test;
@@ -32,7 +33,9 @@ class PostgreSqlTransportSecurityValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(ProfileMismatchException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH))
.hasStackTraceContaining("APP_DATASOURCE_URL")
.hasStackTraceContaining("verify-full");
assertThat(stackTrace(context.getStartupFailure())).doesNotContain(jdbcUrl);
@@ -63,7 +66,9 @@ class PostgreSqlTransportSecurityValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(ProfileMismatchException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH))
.hasStackTraceContaining("conflicting");
assertThat(stackTrace(context.getStartupFailure()))
.doesNotContain("do-not-log")
@@ -3,7 +3,7 @@ package dev.caskeleton.adapter.outbound.persistence.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.assertj.AssertableApplicationContext;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -43,7 +43,7 @@ class RequiredEnvironmentValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure()).hasStackTraceContaining("APP_DATASOURCE_URL");
StartupValidationException ex = startupValidationFailure(context);
StartupFailureException ex = startupValidationFailure(context);
assertThat(ex.getExitCode()).isEqualTo(78);
assertThat(ex.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED);
});
@@ -62,15 +62,18 @@ class RequiredEnvironmentValidatorTest {
});
}
/** Walks the failure chain to the StartupValidationException regardless of any wrapping. */
private static StartupValidationException startupValidationFailure(
/** Walks the failure chain to the StartupFailureException regardless of any wrapping. */
private static StartupFailureException startupValidationFailure(
AssertableApplicationContext context) {
Throwable t = context.getStartupFailure();
while (t != null && !(t instanceof StartupValidationException)) {
while (t != null && !(t instanceof StartupFailureException)) {
t = t.getCause();
}
assertThat(t).isInstanceOf(StartupValidationException.class);
return (StartupValidationException) t;
assertThat(t)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED));
return (StartupFailureException) t;
}
@Configuration
+6 -4
View File
@@ -77,8 +77,10 @@ logstash encoder·Logback은 `compileOnly`다: 애플리케이션의 로깅 스
`StartupFailureException`에 보존하지만 SLF4J throwable 인자로 넘기지 않는다. 따라서 canonical
startup-failure 로그는 운영자가 분류할 수 있는 요약만 남기고 프레임워크/드라이버 stacktrace 를
출력하지 않는다.
- **`StartupFailureException` — 네 실패 원인의 베이스 타입이며 `ExitCodeGenerator`로 exit 코드를 JVM
종료 상태로 만든다.** context refresh 가 실패하면 `SpringApplication`의 `SpringBootExceptionHandler`
- **`StartupFailureException` — 시작 실패의 유일한 타입이다. 원인은 싣고 있는 `StartupErrorCode`가
말하고(`errorCode()`), `ExitCodeGenerator`로 그 코드의 exit 코드를 JVM 종료 상태로 만든다.** 코드마다
subclass(생성자로 코드만 넘기던 4개)를 두던 구조는 없앴다(S6-#13). 생성은 `StartupFailures` 팩토리만
한다 — 생성자는 package-private 이고, 팩토리가 구조화 로그를 함께 남긴다. context refresh 가 실패하면 `SpringApplication`의 `SpringBootExceptionHandler`
(부팅 스레드의 uncaught-exception handler 로 설치됨)가 실패 예외에서 `getExitCode()`를 읽어
`System.exit(code)`를 호출한다 — `main()` 수정이 필요 없다. `IllegalStateException`을 상속하는
이유는 과거 `StartupSafetyValidator`가 `IllegalStateException`을 던졌기 때문으로, 타입드 예외로
@@ -90,6 +92,6 @@ logstash encoder·Logback은 `compileOnly`다: 애플리케이션의 로깅 스
남길 수 있으므로, canonical startup-failure 로그가 이미 찍힌 프로세스에서는 해당
`org.springframework.boot.SpringApplication` 중복 메시지만 logback turbo filter 가 차단한다. 일반
startup failure 가 아닌 예외와 다른 logger/message 는 기존 Spring Boot 로그 경로를 유지한다.
- **`RequiredAdapterDisabledException`은 런타임-라이프사이클의 `ADAPTER_DISABLED`와 의도적으로
구분된다.** 이쪽은 *시작* 검증(필수 어댑터/조정 빈이 꺼져 있음)이고, 후자는 비활성 옵션 어댑터에
- **`REQUIRED_ADAPTER_DISABLED`(`StartupFailures.requiredAdapterDisabled`)는 런타임-라이프사이클의
`ADAPTER_DISABLED`와 의도적으로 구분된다.** 이쪽은 *시작* 검증(필수 어댑터/조정 빈이 꺼져 있음)이고, 후자는 비활성 옵션 어댑터에
대한 *런타임* 호출이다.
@@ -1,15 +0,0 @@
package dev.caskeleton.adapter.outbound.support.startup;
/**
* A Flyway forward-only migration failed during startup (MIGRATION_FAILED, exit 70 — sysexits
* {@code EX_SOFTWARE}). Phase: migration. Wraps the underlying {@code FlywayException} as the cause
* to preserve the root error for triage.
*/
public class MigrationFailedException extends StartupFailureException {
private static final long serialVersionUID = 1L;
public MigrationFailedException(String message, Throwable cause) {
super(StartupErrorCode.MIGRATION_FAILED, message, cause);
}
}
@@ -1,15 +0,0 @@
package dev.caskeleton.adapter.outbound.support.startup;
/**
* An active profile conflicts with an enabled prod-forbidden setting — e.g. a prod-unsafe toggle or
* a forbidden Flyway option left on under the {@code prod} profile (PROFILE_MISMATCH, exit 71 —
* ca-tmpl internal convention, see {@link StartupErrorCode}). Phase: profile-check.
*/
public class ProfileMismatchException extends StartupFailureException {
private static final long serialVersionUID = 1L;
public ProfileMismatchException(String message) {
super(StartupErrorCode.PROFILE_MISMATCH, message, null);
}
}
@@ -1,17 +0,0 @@
package dev.caskeleton.adapter.outbound.support.startup;
/**
* A required capability adapter / coordination bean is disabled or absent at startup
* (REQUIRED_ADAPTER_DISABLED, exit 72 — ca-tmpl internal convention, see {@link StartupErrorCode}).
* Phase: adapter-enablement. Distinct from the runtime-lifecycle {@code ADAPTER_DISABLED}: this is
* a startup validation, not a runtime invoke against a disabled optional adapter. See README for
* the design rationale.
*/
public class RequiredAdapterDisabledException extends StartupFailureException {
private static final long serialVersionUID = 1L;
public RequiredAdapterDisabledException(String message) {
super(StartupErrorCode.REQUIRED_ADAPTER_DISABLED, message, null);
}
}
@@ -1,23 +1,30 @@
package dev.caskeleton.adapter.outbound.support.startup;
import java.util.Objects;
import org.springframework.boot.ExitCodeGenerator;
/**
* Base type for the four startup-failure causes. Implementing {@link ExitCodeGenerator} turns the
* cause's {@link StartupErrorCode#exitCode()} into the JVM exit status when context refresh fails.
* Extends {@link IllegalStateException} for source/behaviour compatibility with the prior {@code
* IllegalStateException}-based startup validation. See README for the design rationale.
* A startup failure. The cause is the {@link StartupErrorCode} it carries — one type, not one
* subclass per code: the four subclasses there were added nothing but a constructor passing their
* code to this one, so a caller could only tell them apart by {@code instanceof}, which is what
* {@link #errorCode()} already answers.
*
* <p>Implementing {@link ExitCodeGenerator} turns the code's {@link StartupErrorCode#exitCode()}
* into the JVM exit status when context refresh fails. Extends {@link IllegalStateException} for
* compatibility with the prior {@code IllegalStateException}-based startup validation. Created only
* by {@link StartupFailures}, which also emits the structured failure log. See README for the
* design rationale.
*/
public abstract class StartupFailureException extends IllegalStateException
public final class StartupFailureException extends IllegalStateException
implements ExitCodeGenerator {
private static final long serialVersionUID = 1L;
private final transient StartupErrorCode errorCode;
protected StartupFailureException(StartupErrorCode errorCode, String message, Throwable cause) {
StartupFailureException(StartupErrorCode errorCode, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
this.errorCode = Objects.requireNonNull(errorCode, "errorCode");
}
public StartupErrorCode errorCode() {
@@ -17,7 +17,7 @@ public final class StartupFailures {
private StartupFailures() {}
public static StartupValidationException envValidation(String detail) {
public static StartupFailureException envValidation(String detail) {
return envValidation(detail, null);
}
@@ -28,24 +28,26 @@ public final class StartupFailures {
* @param cause the failure that proved the configuration wrong; may be {@code null}
* @return the exception to throw
*/
public static StartupValidationException envValidation(String detail, Throwable cause) {
emit(StartupErrorCode.STARTUP_VALIDATION_FAILED, detail, cause);
return new StartupValidationException(detail, cause);
public static StartupFailureException envValidation(String detail, Throwable cause) {
return raise(StartupErrorCode.STARTUP_VALIDATION_FAILED, detail, cause);
}
public static ProfileMismatchException profileMismatch(String detail) {
emit(StartupErrorCode.PROFILE_MISMATCH, detail, null);
return new ProfileMismatchException(detail);
public static StartupFailureException profileMismatch(String detail) {
return raise(StartupErrorCode.PROFILE_MISMATCH, detail, null);
}
public static RequiredAdapterDisabledException requiredAdapterDisabled(String detail) {
emit(StartupErrorCode.REQUIRED_ADAPTER_DISABLED, detail, null);
return new RequiredAdapterDisabledException(detail);
public static StartupFailureException requiredAdapterDisabled(String detail) {
return raise(StartupErrorCode.REQUIRED_ADAPTER_DISABLED, detail, null);
}
public static MigrationFailedException migrationFailed(String detail, Throwable cause) {
emit(StartupErrorCode.MIGRATION_FAILED, detail, cause);
return new MigrationFailedException(detail, cause);
public static StartupFailureException migrationFailed(String detail, Throwable cause) {
return raise(StartupErrorCode.MIGRATION_FAILED, detail, cause);
}
private static StartupFailureException raise(
StartupErrorCode code, String detail, Throwable cause) {
emit(code, detail, cause);
return new StartupFailureException(code, detail, cause);
}
/** Emits the structured startup-failure log. {@code cause} may be {@code null}. */
@@ -1,29 +0,0 @@
package dev.caskeleton.adapter.outbound.support.startup;
/**
* A required environment / configuration value is missing or malformed (STARTUP_VALIDATION_FAILED,
* exit 78 — sysexits {@code EX_CONFIG}). Phase: env-validation.
*/
public class StartupValidationException extends StartupFailureException {
private static final long serialVersionUID = 1L;
public StartupValidationException(String message) {
this(message, null);
}
/**
* Carries the underlying failure alongside the message.
*
* <p>Some configuration is only provably wrong by trying it — a datasource URL is valid text
* until a connection attempt refuses it. Those checks hold a {@code SQLException} whose message
* names the host, the port and the refusal, and dropping it would leave an operator with "could
* not open a connection" and nothing to act on.
*
* @param message the operator-facing detail
* @param cause the failure that proved the configuration wrong; may be {@code null}
*/
public StartupValidationException(String message, Throwable cause) {
super(StartupErrorCode.STARTUP_VALIDATION_FAILED, message, cause);
}
}
@@ -3,51 +3,36 @@ package dev.caskeleton.adapter.outbound.support.startup;
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.CsvSource;
import org.springframework.boot.ExitCodeGenerator;
/**
* Each startup-failure exception must carry its D7 exit code through Spring Boot's {@link
* ExitCodeGenerator} contract. That is the ONLY wiring that makes the custom code the JVM exit
* status: when {@code SpringApplication.run(...)} fails, the registered {@code
* SpringBootExceptionHandler} reads {@code getExitCode()} off the failing exception and calls
* {@code System.exit(code)} — no {@code main()} change is required (and wrapping main with {@code
* System.exit(SpringApplication.exit(run(...)))} would instead close the context and exit 0 on a
* healthy boot, killing a long-running server — see design record F2 deviation).
* Each startup failure carries its D7 exit code through Spring Boot's {@link ExitCodeGenerator}
* contract. That is the ONLY wiring that makes the custom code the JVM exit status: when {@code
* SpringApplication.run(...)} fails, the registered {@code SpringBootExceptionHandler} reads {@code
* getExitCode()} off the failing exception and calls {@code System.exit(code)}.
*/
class StartupFailureExceptionTest {
@Test
void everyStartupExceptionIsAnExitCodeGenerator() {
assertThat((ExitCodeGenerator) new StartupValidationException("env missing")).isNotNull();
assertThat((ExitCodeGenerator) new ProfileMismatchException("profile")).isNotNull();
assertThat((ExitCodeGenerator) new RequiredAdapterDisabledException("adapter")).isNotNull();
assertThat((ExitCodeGenerator) new MigrationFailedException("migration", null)).isNotNull();
}
@ParameterizedTest
@CsvSource({
"STARTUP_VALIDATION_FAILED, 78",
"MIGRATION_FAILED, 70",
"PROFILE_MISMATCH, 71",
"REQUIRED_ADAPTER_DISABLED, 72"
})
void theExitCodeIsTheCarriedErrorCodesD7Status(StartupErrorCode code, int exitCode) {
// when
ExitCodeGenerator failure = new StartupFailureException(code, "x", null);
@Test
void exitCodesMatchTheD7Standard() {
assertThat(new StartupValidationException("x").getExitCode()).isEqualTo(78);
assertThat(new MigrationFailedException("x", null).getExitCode()).isEqualTo(70);
assertThat(new ProfileMismatchException("x").getExitCode()).isEqualTo(71);
assertThat(new RequiredAdapterDisabledException("x").getExitCode()).isEqualTo(72);
}
@Test
void eachExceptionExposesItsRegistryErrorCode() {
assertThat(new StartupValidationException("x").errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED);
assertThat(new MigrationFailedException("x", null).errorCode())
.isEqualTo(StartupErrorCode.MIGRATION_FAILED);
assertThat(new ProfileMismatchException("x").errorCode())
.isEqualTo(StartupErrorCode.PROFILE_MISMATCH);
assertThat(new RequiredAdapterDisabledException("x").errorCode())
.isEqualTo(StartupErrorCode.REQUIRED_ADAPTER_DISABLED);
// then
assertThat(failure.getExitCode()).isEqualTo(exitCode);
}
@Test
void remainsAnIllegalStateExceptionSoExistingStartupGuardsStayCompatible() {
// StartupSafetyValidator (feature-env-driven) historically threw IllegalStateException;
// keeping that supertype means existing callers / tests asserting on it stay green.
assertThat(new ProfileMismatchException("x")).isInstanceOf(IllegalStateException.class);
assertThat(new StartupFailureException(StartupErrorCode.PROFILE_MISMATCH, "x", null))
.isInstanceOf(IllegalStateException.class);
}
}
@@ -42,7 +42,7 @@ class StartupFailuresTest {
@Test
void envValidationFailureLogsAllThreeStructuredFieldsAtErrorLevel() {
StartupValidationException ex = StartupFailures.envValidation("APP_DATASOURCE_URL is blank");
StartupFailureException ex = StartupFailures.envValidation("APP_DATASOURCE_URL is blank");
assertThat(ex.getExitCode()).isEqualTo(78);
ILoggingEvent event = singleEvent();
@@ -57,7 +57,7 @@ class StartupFailuresTest {
@Test
void migrationFailurePreservesCauseAndLogsMigrationPhase() {
RuntimeException root = new RuntimeException("V2__x.sql failed");
MigrationFailedException ex = StartupFailures.migrationFailed("Flyway migrate failed", root);
StartupFailureException ex = StartupFailures.migrationFailed("Flyway migrate failed", root);
assertThat(ex.getExitCode()).isEqualTo(70);
assertThat(ex).hasCause(root);
+1 -1
View File
@@ -60,7 +60,7 @@ configurations, Redis as one 376-line class.
capability is a commented `runtimeOnly` line in `build.gradle`; the default composition is web,
observability, the cores, support and identifier. This leaf keeps no list of capabilities: no
switch registry, no cross-capability dependency validator, no activation endpoint. Component scan
covers `dev.caskeleton.bootstrap` only; web (`WebAdapterAutoConfiguration`) and support
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
+5 -13
View File
@@ -21,7 +21,7 @@ WebSocket, gRPC, 파일 서버, 알림)는 `build.gradle`에 주석 처리된 `r
있다. 주석을 풀면 그 모듈이 자기 `AutoConfiguration.imports`와 설정 기본값으로 켜지고, 줄을 지우면 함께
사라진다. 있는 모듈은 자기 `enabled` 키(기본 `true`)를 `false`로 줄 때만 꺼진다. 합성 루트는 capability
목록을 따로 들고 있지 않다(스위치 목록, scan 제외 정규식, 의존 검사기 없음). component scan은
`dev.caskeleton.bootstrap`만 보고, web(`WebAdapterAutoConfiguration`)과 support(`OutboundSupportConfig`)도
`dev.caskeleton.bootstrap`만 보고, web(`WebAdapterAutoConfiguration`·`WebSecurityAutoConfiguration`)과 support(`OutboundSupportConfig`)도
자기 auto-configuration으로 들어온다.
- 줄마다 필요한 env와 끄는 키: [src/README.md](../README.md)의 "기능 추가 = 한 줄 + env" 표.
@@ -191,18 +191,10 @@ README의 "startup" 절에 있다.
## concurrency — 도메인 컨텍스트 전파 전략 조립
### DomainContextConfig
- **`DomainContextPropagator`를 빈으로 노출하고, 설정에서 고른 `DomainContextStrategy`로
`DomainContextPropagatorFactory`를 통해 조립한다.** `application-core`는 설정을 직접 읽지 않는다는
원칙 때문에, 전략 해석과 propagator 생성은 composition root(여기)에서 끝내고 완성된 propagator 만
주입한다. 그래서 use case 코드는 어떤 전파 전략을 쓰는지 몰라도 되고, 전략 교체는 코드가 아니라
설정으로만 일어난다.
### DomainContextSettings
- **`ca-skeleton.domain-context.strategy`가 비어 있으면 `THREAD_LOCAL`로 기본값을 채운다.** 스켈레톤은
"설정 없이도 바로 동작하는 기본값"을 제공하는 것을 원칙으로 하므로, 전략을 강제로 지정하게 만들지
않고 가장 안전한 `THREAD_LOCAL`을 디폴트로 둔다. 이 전략은 rate-limit 알고리즘처럼 전용 환경변수
를 두지 않는데, 보안 비밀이나 배포별 값이 아니라 운영상의 선택지라 설정 바인딩만으로 충분하기
때문이다.
- **`DomainContextPropagator`를 빈으로 노출하고 `ThreadLocalDomainContextPropagator`를 직접 만든다.**
`application-core`는 설정을 직접 읽지 않으므로 propagator 생성은 composition root(여기)에서 끝내고
완성된 propagator만 주입한다. 제공하는 전략이 하나뿐이라 선택 설정(strategy enum·factory·설정 키)은
두지 않는다. 두 번째 전략이 생기면 그 구현과 선택 설정을 함께 추가한다.
---
+1
View File
@@ -173,6 +173,7 @@ dependencies {
testImplementation(testFixtures(project(':adapter:inbound:web')))
// The idempotency composition tests drive the executor over the port owner's shared fake store.
testImplementation(testFixtures(project(':application-core')))
testImplementation(testFixtures(project(':shared-contract')))
// The opt-in web library is in no shipped composition. Runtime-only for the tests so the
// whole-repository ArchUnit import (architectureTest runs on the test runtime classpath) still
// reads its classes; no test source may name one of its types. It cannot reach a shipped
@@ -88,6 +88,7 @@ class ArchRuleDiscoveryContractTest {
"APPLICATION_DOES_NOT_USE_SPRING_TRANSACTIONAL_ANNOTATION",
"APPLICATION_HAS_NO_DIAGNOSTIC_FRAMEWORK",
"APPLICATION_METHODS_DO_NOT_ACCEPT_WEB_DTOS",
"BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS",
"BOOTSTRAP_USES_ONLY_THE_PERSISTENCE_EXPORT_SURFACE",
"BULK_WRITE_CAPABILITY_REQUIRES_WRITE_REPOSITORY_ACCESS",
"COMPOSITION_ROOT_DOES_NOT_IMPLEMENT_APPLICATION_OR_DOMAIN_PORTS",
@@ -1,11 +1,14 @@
package dev.caskeleton.bootstrap.architecture;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.stereotype.Component;
/**
* The composition root assembles; it does not implement application ports (BOOT-017).
@@ -58,4 +61,28 @@ class CompositionRootBoundaryArchitectureTest {
+ "an adapter/outbound/* leaf — see LoggingNotificationAudit and "
+ "MicrometerNotificationMetrics in adapter/outbound/notification for the shape.")
.allowEmptyShould(true);
/**
* NEW-12: every stereotype in {@code bootstrap.autoconfigure} is an {@code @AutoConfiguration}.
*
* <p>The package sits inside {@code @SpringBootApplication}'s component scan. Boot's {@code
* AutoConfigurationExcludeFilter} keeps the registered roots out of that scan, so their
* conditions decide. A plain {@code @Configuration} or {@code @Component} added next to them
* would not be filtered: the scan would register it unconditionally, whatever switch its
* neighbour honours.
*/
@ArchTest
static final ArchRule BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS =
classes()
.that()
.resideInAPackage("dev.caskeleton.bootstrap.autoconfigure..")
.and()
.areMetaAnnotatedWith(Component.class)
.should()
.beAnnotatedWith(AutoConfiguration.class)
.as(
"NEW-12: bootstrap.autoconfigure is inside the component scan; only @AutoConfiguration "
+ "roots (excluded from the scan and gated by their own conditions) may live "
+ "there. Put a helper configuration in a package outside the scan or import it "
+ "from a root.");
}
@@ -72,8 +72,7 @@ class ForbiddenApiArchitectureTest {
// authorization contract consumed by AuthorizationPort.
"dev.caskeleton.shared.security",
// feature-runtime-context-propagation-contract: the domain-context
// propagation port + default ThreadLocal strategy + factory
// (swappable abstraction, the rate-limit pattern).
// propagation port + its ThreadLocal implementation.
"dev.caskeleton.shared.concurrency");
@Override
@@ -166,17 +165,16 @@ class ForbiddenApiArchitectureTest {
.allowEmptyShould(true);
// ---- feature-runtime-context-propagation-contract (domain extension of B6) ----
// Strategy guard for the domain-context propagation seam. The shipped default is
// ThreadLocal (DomainContextStrategy.THREAD_LOCAL — plain ThreadLocal, no preview
// API); the MICROMETER / SCOPED_VALUE strategies are reserved-but-unshipped. This
// Guard for the domain-context propagation seam. The one shipped implementation is
// ThreadLocalDomainContextPropagator (plain ThreadLocal, no preview API). This
// rule keeps the two Java 21 PREVIEW primitives (ScopedValue / StructuredTaskScope)
// out of production code until the SCOPED_VALUE strategy is actually activated
// through the factory seam. The build has no --enable-preview (build fact C1), so
// out of production code until a ScopedValue implementation is deliberately added. The build has
// no --enable-preview (build fact C1), so
// those APIs cannot even compile today — the compile gate is the first line of
// defence and is why a compilable violation fixture is infeasible; this rule is the
// dormant defence-in-depth that fires the moment --enable-preview is enabled and
// someone reaches for the preview primitive without adding the strategy + factory
// case. It is NOT the deferred S4/D7 activation-correctness rule
// someone reaches for the preview primitive without adding that implementation. It is NOT the
// deferred S4/D7 activation-correctness rule
// (UNSUPPORTED_IMPL_DECISION — rule shape intentionally not invented). The
// implicit-inheritance ban (S3, the ThreadLocal default's contract) cross-cites
// NO_INHERITABLE_THREAD_LOCAL above (owner: boundary-validation B6).
@@ -194,7 +192,7 @@ class ForbiddenApiArchitectureTest {
.as(
"the domain-context default is ThreadLocal; the ScopedValue / "
+ "StructuredTaskScope (preview) strategy must not appear in production "
+ "code until activated through the DomainContextStrategy + factory seam "
+ "code until a ScopedValue DomainContextPropagator is deliberately added "
+ "(feature-runtime-context-propagation-contract S2)")
.allowEmptyShould(true);
@@ -2,31 +2,59 @@ package dev.caskeleton.bootstrap.architecture;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
import java.util.Set;
import org.springframework.core.env.Environment;
/** BOOT-002: Spring active-profile extraction has one composition-root owner. */
@AnalyzeClasses(
packages = "dev.caskeleton.bootstrap",
importOptions = ProductionClassImportOption.class)
/**
* BOOT-002: Spring active-profile extraction has a fixed, named set of owners across the whole
* repository, not only inside app-bootstrap.
*
* <p>{@code RuntimeProfileSnapshot} is the bridge for every leaf that may depend on {@code
* adapter:outbound:support}. GraphQL and object storage may not (their registered edges do not
* include support), and fileserver and the HTTP client read the profiles once inside their own
* capability guard, so those four are listed by name. A new reader anywhere else — a leaf that
* starts judging "is this production" from raw profile names on its own — fails here and has to
* either go through the snapshot or be added to this list on purpose. The vendored {@code
* messaging} platform and the {@code sample} fixture are outside this application's policy.
*/
@AnalyzeClasses(packages = "dev.caskeleton", importOptions = ProductionClassImportOption.class)
class RuntimeProfileAccessArchitectureTest {
/** Every production class allowed to call {@code Environment#getActiveProfiles}. */
static final Set<String> PROFILE_READERS =
Set.of(
"dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot",
"dev.caskeleton.adapter.inbound.graphql.autoconfigure.GraphQlPlatformAutoConfiguration",
"dev.caskeleton.adapter.outbound.fileserver.platform.autoconfigure"
+ ".FileserverSecurityConfiguration",
"dev.caskeleton.adapter.outbound.httpclient.autoconfigure"
+ ".HttpClientProfileAutoConfiguration",
"dev.caskeleton.adapter.outbound.objectstorage.config.ObjectStorageCapabilityConfig");
private static final DescribedPredicate<JavaClass> A_NAMED_PROFILE_READER =
DescribedPredicate.describe(
"a named profile reader", javaClass -> PROFILE_READERS.contains(javaClass.getName()));
@ArchTest
static final ArchRule ACTIVE_PROFILES_ARE_READ_ONLY_BY_THE_SNAPSHOT_BRIDGE =
noClasses()
.that()
.resideInAPackage("dev.caskeleton.bootstrap..")
.resideInAPackage("dev.caskeleton..")
.and()
.doNotHaveFullyQualifiedName(RuntimeProfileSnapshot.class.getName())
.resideOutsideOfPackages("dev.caskeleton.messaging..", "dev.caskeleton.sample..")
.and(DescribedPredicate.not(A_NAMED_PROFILE_READER))
.should()
.callMethod(Environment.class, "getActiveProfiles")
.as(
"BOOT-002: app-bootstrap production code must read Spring active profiles through "
+ "RuntimeProfileSnapshot; RuntimeEnvironment remains the vocabulary/semantics "
+ "SSOT and direct Environment#getActiveProfiles calls re-create profile-policy "
+ "drift.")
"BOOT-002: production code reads Spring active profiles through "
+ "RuntimeProfileSnapshot, or is one of the named readers in "
+ "RuntimeProfileAccessArchitectureTest.PROFILE_READERS; RuntimeEnvironment "
+ "remains the vocabulary/semantics SSOT and a new direct "
+ "Environment#getActiveProfiles call re-creates profile-policy drift.")
.allowEmptyShould(true);
}
@@ -411,8 +411,10 @@ class FileserverCompositionIntegrationTest {
// The web adapter publishes its own auto-configuration (security, envelope, principal
// pseudonymization); the Fileserver routes under test are reached through MockMvc without it.
@EnableAutoConfiguration(
excludeName =
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration")
excludeName = {
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration"
})
@ComponentScan(
basePackages = {
"dev.caskeleton.adapter.inbound.web.fileserver",
@@ -145,7 +145,8 @@ class ObjectStorageCompositionIntegrationTest {
"org.springframework.boot.data.jpa.autoconfigure.DataJpaRepositoriesAutoConfiguration",
"org.springframework.boot.flyway.autoconfigure.FlywayAutoConfiguration",
// Web publishes its own auto-configuration; this test drives the port, not HTTP.
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration"
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration"
})
@Import(ObjectStorageCapabilityConfig.class)
static class ObjectStorageRuntime {}
@@ -221,11 +221,13 @@ class DurableOperationCompositionIntegrationTest {
/** The shipped composition over a datasource, plus the web authorization pieces it relies on. */
@SpringBootConfiguration
// The web adapter's root would add the JWT/session security chain, which needs an issuer; the
// The web security root would add the JWT/session security chain, which needs an issuer; the
// permission check lives in the method-security advisor imported below.
@EnableAutoConfiguration(
excludeName =
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration")
excludeName = {
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration",
"dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration"
})
@EnableConfigurationProperties(RolePermissionPolicy.class)
@Import({
// The JPA audit port reads the domain context; the running application gets it from here.
@@ -1,18 +1,20 @@
package dev.caskeleton.bootstrap.concurrency;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.DomainContextPropagatorFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/** Wires the {@link DomainContextPropagator} bean. See README for the design rationale. */
/**
* 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
@EnableConfigurationProperties(DomainContextSettings.class)
public class DomainContextConfig {
@Bean
public DomainContextPropagator domainContextPropagator(DomainContextSettings properties) {
return DomainContextPropagatorFactory.create(properties.strategy());
public DomainContextPropagator domainContextPropagator() {
return new ThreadLocalDomainContextPropagator();
}
}
@@ -1,19 +0,0 @@
package dev.caskeleton.bootstrap.concurrency;
import dev.caskeleton.shared.concurrency.DomainContextStrategy;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Domain-context propagation strategy selection. See README for the design rationale.
*
* @param strategy the propagation strategy; {@code null} → {@code THREAD_LOCAL}
*/
@ConfigurationProperties(prefix = "ca-skeleton.domain-context")
public record DomainContextSettings(DomainContextStrategy strategy) {
public DomainContextSettings {
if (strategy == null) {
strategy = DomainContextStrategy.THREAD_LOCAL;
}
}
}
@@ -5,8 +5,7 @@ import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.shared.concurrency.DomainContextKey;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.DomainContextPropagatorFactory;
import dev.caskeleton.shared.concurrency.DomainContextStrategy;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -29,8 +28,7 @@ class AsyncContextTaskDecoratorTest {
private static final DomainContextKey<String> TENANT =
DomainContextKey.of("tenant_ctx", String.class);
private final DomainContextPropagator propagator =
DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL);
private final DomainContextPropagator propagator = new ThreadLocalDomainContextPropagator();
private final AsyncContextTaskDecorator decorator = new AsyncContextTaskDecorator(propagator);
@AfterEach
@@ -5,8 +5,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.DomainContextPropagatorFactory;
import dev.caskeleton.shared.concurrency.DomainContextStrategy;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@@ -31,8 +30,7 @@ class AsyncExceptionPropagationTest {
@Test
void submitPathSurfacesTaskExceptionViaFuture() {
AsyncExecutorConfig config = new AsyncExecutorConfig();
DomainContextPropagator propagator =
DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL);
DomainContextPropagator propagator = new ThreadLocalDomainContextPropagator();
BackgroundJobMetrics metrics =
new BackgroundJobMetrics(
new StaticListableBeanFactory()
@@ -59,8 +57,7 @@ class AsyncExceptionPropagationTest {
@Test
void executePathDecoratorRethrowsAndDoesNotSwallow() {
DomainContextPropagator propagator =
DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL);
DomainContextPropagator propagator = new ThreadLocalDomainContextPropagator();
AsyncContextTaskDecorator decorator = new AsyncContextTaskDecorator(propagator);
Runnable decorated =
decorator.decorate(
@@ -3,8 +3,7 @@ package dev.caskeleton.bootstrap.async;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.DomainContextPropagatorFactory;
import dev.caskeleton.shared.concurrency.DomainContextStrategy;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import java.lang.reflect.Field;
import java.util.concurrent.RejectedExecutionHandler;
import org.junit.jupiter.api.Test;
@@ -110,7 +109,7 @@ class AsyncExecutorConfigTest {
static class PropagatorConfig {
@Bean
DomainContextPropagator domainContextPropagator() {
return DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL);
return new ThreadLocalDomainContextPropagator();
}
}
@@ -3,7 +3,8 @@ package dev.caskeleton.bootstrap.async;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.bind.Binder;
@@ -49,7 +50,9 @@ class AsyncExecutorSettingsTest {
@Test
void coreSizeBelowOneIsRejected() {
assertThatThrownBy(() -> new AsyncExecutorSettings(0, 50, 200))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("APP_ASYNC_EXECUTOR_CORE_SIZE");
}
@@ -58,14 +61,18 @@ class AsyncExecutorSettingsTest {
@Test
void maxSizeBelowOneIsRejected() {
assertThatThrownBy(() -> new AsyncExecutorSettings(1, 0, 200))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("APP_ASYNC_EXECUTOR_MAX_SIZE");
}
@Test
void maxSizeBelowCoreSizeIsRejected() {
assertThatThrownBy(() -> new AsyncExecutorSettings(20, 10, 200))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("positive_int_ge_core");
}
@@ -74,7 +81,9 @@ class AsyncExecutorSettingsTest {
@Test
void queueCapacityBelowOneIsRejected() {
assertThatThrownBy(() -> new AsyncExecutorSettings(10, 50, 0))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("APP_ASYNC_EXECUTOR_QUEUE_CAPACITY");
}
@@ -83,7 +92,9 @@ class AsyncExecutorSettingsTest {
// D7 / SF-TPTE-C1: Integer.MAX_VALUE is the unbounded sentinel and is forbidden —
// an unbounded queue makes max-size unreachable (TPE-JDK21-C3).
assertThatThrownBy(() -> new AsyncExecutorSettings(10, 50, Integer.MAX_VALUE))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("bounded");
}
}
@@ -7,8 +7,7 @@ import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
import dev.caskeleton.shared.concurrency.DomainContextPropagatorFactory;
import dev.caskeleton.shared.concurrency.DomainContextStrategy;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
@@ -165,7 +164,7 @@ class AsyncGracefulShutdownBehaviorTest {
static class PropagatorConfig {
@Bean
DomainContextPropagator domainContextPropagator() {
return DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL);
return new ThreadLocalDomainContextPropagator();
}
}
}
@@ -3,7 +3,8 @@ 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.StartupValidationException;
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;
@@ -99,7 +100,9 @@ class IdempotencySettingsTest {
// then
assertThat(thrown)
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("ca-skeleton.capabilities.idempotency." + message);
}
@@ -115,7 +118,9 @@ class IdempotencySettingsTest {
// then
assertThat(thrown)
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("ca-skeleton.capabilities.idempotency." + message);
}
@@ -130,7 +135,9 @@ class IdempotencySettingsTest {
// then
assertThat(thrown)
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining(
"ca-skeleton.capabilities.idempotency.policy-revision must be positive");
}
@@ -3,7 +3,8 @@ 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.StartupValidationException;
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;
@@ -48,35 +49,45 @@ class OutboxSettingsTest {
@Test
void rejectsZeroBatchSize() {
assertThatThrownBy(() -> new OutboxSettings(true, false, null, 0, null, null, null))
.isInstanceOf(StartupValidationException.class)
.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))
.isInstanceOf(StartupValidationException.class)
.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))
.isInstanceOf(StartupValidationException.class)
.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))
.isInstanceOf(StartupValidationException.class)
.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))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("reaperInterval");
}
@@ -84,14 +95,18 @@ class OutboxSettingsTest {
void rejectsNegativeReaperInterval() {
assertThatThrownBy(
() -> new OutboxSettings(true, false, null, null, null, Duration.ofMinutes(-1), null))
.isInstanceOf(StartupValidationException.class)
.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))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("publishedRetention");
}
@@ -99,7 +114,9 @@ class OutboxSettingsTest {
void rejectsNegativePublishedRetention() {
assertThatThrownBy(
() -> new OutboxSettings(true, false, null, null, null, null, Duration.ofHours(-1)))
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasMessageContaining("publishedRetention");
}
}
@@ -3,6 +3,7 @@ package dev.caskeleton.bootstrap.autoconfigure.tracing;
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.shared.tracing.SpanErrorRecorder;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.tracing.Tracer;
@@ -94,8 +95,10 @@ class TracingActivationContextTest {
HibernateJpaAutoConfiguration.class,
DataJpaRepositoriesAutoConfiguration.class,
FlywayAutoConfiguration.class,
// The web adapter's own root (security, filters, settings) is not what this slice is about.
WebAdapterAutoConfiguration.class
// The web adapter's own roots (security, filters, settings) are not what this slice is
// about.
WebAdapterAutoConfiguration.class,
WebSecurityAutoConfiguration.class
})
@Import(TracingConfig.class)
static class MinimalTracingApp {}
@@ -4,7 +4,8 @@ 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.StartupValidationException;
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;
@@ -187,7 +188,9 @@ class TracingSettingsTest {
@Test
void nonBlankInvalidSampleRateStillThrows() {
assertThatThrownBy(() -> new TracingSettings(true, "1.5", null))
.isInstanceOf(StartupValidationException.class);
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED));
}
// ---- F3: sampleRateValue() precondition contract ----
@@ -5,6 +5,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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 org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@@ -103,8 +104,10 @@ class ActuatorSecurityHttpTest {
HibernateJpaAutoConfiguration.class,
DataJpaRepositoriesAutoConfiguration.class,
FlywayAutoConfiguration.class,
// The web adapter's own root (security, filters, settings) is not what this slice is about.
WebAdapterAutoConfiguration.class
// The web adapter's own roots (security, filters, settings) are not what this slice is
// about.
WebAdapterAutoConfiguration.class,
WebSecurityAutoConfiguration.class
})
@Import(ManagementSecurityConfig.class)
static class MinimalActuatorApp {}
@@ -85,7 +85,6 @@ class ConfigurationNamespaceContractTest {
"ca-skeleton.async.executor",
"ca-skeleton.bootstrap",
"ca-skeleton.capabilities.idempotency",
"ca-skeleton.domain-context",
"ca-skeleton.logging",
"ca-skeleton.outbox",
"ca-skeleton.privacy",
@@ -141,7 +140,7 @@ class ConfigurationNamespaceContractTest {
assertThat(found)
.as("the scan must find the leaf's settings prefixes, or this check passes vacuously")
.hasSizeGreaterThan(10);
.isNotEmpty();
assertThat(found)
.as(
"a settings prefix that is not recorded here is a namespace decision nobody reviewed. "
@@ -7,8 +7,7 @@ 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.shared.concurrency.DomainContextPropagatorFactory;
import dev.caskeleton.shared.concurrency.DomainContextStrategy;
import dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator;
import dev.caskeleton.shared.response.ResponseMeta;
import dev.caskeleton.shared.tracing.BaggageAllowlist;
import io.micrometer.core.instrument.Meter;
@@ -294,7 +293,7 @@ class DistributedTracingContractTest {
*/
@Test
void asyncDecoratorCarriesCorrelationIdOntoWorkerThread() throws Exception {
var propagator = DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL);
var propagator = new ThreadLocalDomainContextPropagator();
var decorator = new AsyncContextTaskDecorator(propagator);
MDC.put(MdcKeys.CORRELATION_ID, "corr-trace-contract-test");
@@ -2,7 +2,8 @@ package dev.caskeleton.bootstrap.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.ProfileMismatchException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
@@ -33,7 +34,9 @@ class ErrorDetailExposureSafetyValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(ProfileMismatchException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e -> assertThat(e.errorCode()).isEqualTo(StartupErrorCode.PROFILE_MISMATCH))
.hasStackTraceContaining(namedInFailure);
});
}
@@ -12,6 +12,7 @@ import dev.caskeleton.adapter.inbound.web.filter.CacheControlFilter;
import dev.caskeleton.adapter.inbound.web.filter.RequestLoggingFilter;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebMvcPlatformAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration;
import dev.caskeleton.adapter.inbound.web.mvc.filter.WebMvcRequestIdFilter;
import dev.caskeleton.adapter.inbound.web.settings.PresentationSettings;
import dev.caskeleton.bootstrap.CaSkeletonApplication;
@@ -57,6 +58,7 @@ import org.springframework.web.bind.annotation.RestController;
// MVC slice leaves out; the order test compares the request-id filter against that registration.
@ImportAutoConfiguration({
WebAdapterAutoConfiguration.class,
WebSecurityAutoConfiguration.class,
WebMvcPlatformAutoConfiguration.class,
SecurityFilterAutoConfiguration.class
})
@@ -2,7 +2,8 @@ package dev.caskeleton.bootstrap.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException;
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.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Bean;
@@ -28,7 +29,11 @@ class RuntimeNumericBoundsValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_SERVER_TOMCAT_MAX_THREADS")
.hasStackTraceContaining(">= 1");
});
@@ -42,7 +47,11 @@ class RuntimeNumericBoundsValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_SERVER_TOMCAT_MIN_SPARE_THREADS");
});
}
@@ -2,7 +2,8 @@ package dev.caskeleton.bootstrap.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.StartupValidationException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import java.util.Arrays;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
@@ -47,7 +48,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("__LOCAL_DEV_")
.hasStackTraceContaining("APP_DATASOURCE_PASSWORD");
});
@@ -68,7 +73,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("__LOCAL_DEV_")
.hasStackTraceContaining("APP_DATASOURCE_PASSWORD")
.hasStackTraceContaining("APP_PRIVACY_PSEUDONYMIZATION_SALT")
@@ -103,7 +112,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_DATASOURCE_PASSWORD");
});
}
@@ -118,7 +131,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_DATASOURCE_PASSWORD");
});
}
@@ -177,7 +194,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_CACHE_REDIS_KEY_HMAC_SECRET");
});
}
@@ -216,7 +237,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_RATE_LIMIT_REDIS_KEY_HMAC_SECRET");
});
}
@@ -262,7 +287,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_IDEMPOTENCY_REDIS_KEY_HMAC_SECRET");
});
}
@@ -280,7 +309,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_LEASE_REDIS_KEY_HMAC_SECRET");
});
}
@@ -299,7 +332,11 @@ class SecretSourceValidatorTest {
context -> {
assertThat(context).hasFailed();
assertThat(context.getStartupFailure())
.isInstanceOf(StartupValidationException.class)
.isInstanceOfSatisfying(
StartupFailureException.class,
e ->
assertThat(e.errorCode())
.isEqualTo(StartupErrorCode.STARTUP_VALIDATION_FAILED))
.hasStackTraceContaining("APP_SESSION_REDIS_KEY_HMAC_SECRET");
});
}
@@ -2,7 +2,7 @@ package dev.caskeleton.bootstrap.runtime;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.startup.RequiredAdapterDisabledException;
import dev.caskeleton.adapter.outbound.support.startup.StartupErrorCode;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.application.lock.DistributedLockPort;
import dev.caskeleton.bootstrap.settings.RuntimeSafetySettings;
@@ -35,9 +35,8 @@ class StartupSafetyValidatorTest {
assertThat(context.getStartupFailure())
.hasStackTraceContaining("APP_MULTI_INSTANCE_ENABLED")
.hasStackTraceContaining("distributedLockProvider");
StartupFailureException ex =
startupFailure(context, RequiredAdapterDisabledException.class);
assertThat(ex.getExitCode()).isEqualTo(72);
StartupFailureException ex = startupFailure(context);
assertThat(ex.errorCode()).isEqualTo(StartupErrorCode.REQUIRED_ADAPTER_DISABLED);
});
}
@@ -68,13 +67,12 @@ class StartupSafetyValidatorTest {
runner.run(context -> assertThat(context).hasNotFailed());
}
private static StartupFailureException startupFailure(
AssertableApplicationContext context, Class<? extends StartupFailureException> type) {
private static StartupFailureException startupFailure(AssertableApplicationContext context) {
Throwable failure = context.getStartupFailure();
while (failure != null && !type.isInstance(failure)) {
while (failure != null && !(failure instanceof StartupFailureException)) {
failure = failure.getCause();
}
assertThat(failure).isInstanceOf(type);
assertThat(failure).isInstanceOf(StartupFailureException.class);
return (StartupFailureException) failure;
}
@@ -3,7 +3,8 @@ package dev.caskeleton.bootstrap.runtime.startup;
import static org.assertj.core.api.Assertions.assertThat;
import dev.caskeleton.adapter.outbound.support.CapabilityStartupValidationException;
import dev.caskeleton.adapter.outbound.support.startup.MigrationFailedException;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailureException;
import dev.caskeleton.adapter.outbound.support.startup.StartupFailures;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanCreationException;
@@ -13,8 +14,9 @@ class StartupFailureExceptionReporterTest {
@Test
void reportsWrappedStartupFailureAsAlreadyHandled() {
MigrationFailedException startupFailure =
new MigrationFailedException("Flyway forward-only migration failed during startup", null);
StartupFailureException startupFailure =
StartupFailures.migrationFailed(
"Flyway forward-only migration failed during startup", null);
BeanCreationException wrapped =
new BeanCreationException("flywayInitializer", "failed", startupFailure);
@@ -1,5 +1,6 @@
package dev.caskeleton.application.operation;
import dev.caskeleton.application.command.Command;
import dev.caskeleton.application.idempotency.RequestFingerprint;
import java.time.Duration;
import java.util.Objects;
@@ -29,7 +30,8 @@ public record OperationCommand(
RequestFingerprint fingerprint,
String payload,
String eventType,
Duration timeToLive) {
Duration timeToLive)
implements Command {
/**
* The outbox event type for an operation whose caller does not publish an event of its own, such

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