diff --git a/docs/architecture/graphql-api-surface.txt b/docs/architecture/graphql-api-surface.txt index 1b74a297..b1e149b1 100644 --- a/docs/architecture/graphql-api-surface.txt +++ b/docs/architecture/graphql-api-surface.txt @@ -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 diff --git a/docs/capability-status.md b/docs/capability-status.md index e1efc794..4410cd30 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -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) | diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index ea76ad27..6d6ed884 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -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 diff --git a/docs/reviews/2026-09-25-review-followup-results/W3-P25.md b/docs/reviews/2026-09-25-review-followup-results/W3-P25.md new file mode 100644 index 00000000..756b4014 --- /dev/null +++ b/docs/reviews/2026-09-25-review-followup-results/W3-P25.md @@ -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 `) 확인 후 원복 → PASS | +| A-4b | 완료 | `SubmitDurableOperationUseCase implements CommandUseCase`, `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-`)와 충돌할 수 있어 설계 결정이 더 필요하다. 명령 경로 고정이 더 작다 | + +집계: 완료 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`. diff --git a/docs/reviews/2026-09-25-review-followup-status.md b/docs/reviews/2026-09-25-review-followup-status.md index a8efab6d..f57d70f4 100644 --- a/docs/reviews/2026-09-25-review-followup-status.md +++ b/docs/reviews/2026-09-25-review-followup-status.md @@ -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 `) 확인 후 원복 → 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`)
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`를 구현하고 `submit`→`handle`로 이름 변경(Get/Cancel과 같은 모양) | +| A-4b | Required | `SubmitDurableOperationUseCase`가 `CommandUseCase`를 구현하지 않음(자체 `submit` 메서드), production 호출자 0 | 완료 | Wave 3 W3-P25 (Wave 3 라운드 2 커밋): `SubmitDurableOperationUseCase implements CommandUseCase`, `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`를 구현하고 `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`
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 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 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 검증기 이동은 같은 사유로 결정 필요. 승인자: 저장소 소유자 결정 필요
결정 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로 열어 둔 질문). 승인자: 저장소 소유자 결정 필요
결정 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와 함께)
결정 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` 표 하나로 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` 공존
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-`)와 충돌할 수 있어 설계 결정이 더 필요하다. 명령 경로 고정이 더 작다 | - | 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 | 불필요한 설정 삭제 또는 이유 주석 | diff --git a/docs/superpowers/plans/2026-09-25-review-followup.md b/docs/superpowers/plans/2026-09-25-review-followup.md index 0abb8637..a93e97c0 100644 --- a/docs/superpowers/plans/2026-09-25-review-followup.md +++ b/docs/superpowers/plans/2026-09-25-review-followup.md @@ -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 마무리 커밋) diff --git a/src/.env.example b/src/.env.example index b85eba49..ef922a77 100644 --- a/src/.env.example +++ b/src/.env.example @@ -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= diff --git a/src/adapter/inbound/graphql/CLAUDE.md b/src/adapter/inbound/graphql/CLAUDE.md index c630831a..357b563f 100644 --- a/src/adapter/inbound/graphql/CLAUDE.md +++ b/src/adapter/inbound/graphql/CLAUDE.md @@ -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` | diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDataLoaderConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDataLoaderConfiguration.java new file mode 100644 index 00000000..e756d35d --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlDataLoaderConfiguration.java @@ -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. + * + *

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. + * + *

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); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlErrorConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlErrorConfiguration.java new file mode 100644 index 00000000..2e86a74e --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlErrorConfiguration.java @@ -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. + * + *

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); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlExecutionChainConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlExecutionChainConfiguration.java new file mode 100644 index 00000000..47f83b4a --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlExecutionChainConfiguration.java @@ -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. + * + *

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. + * + *

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. + * + *

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); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java new file mode 100644 index 00000000..2503c234 --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlObservationConfiguration.java @@ -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. + * + *

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. + * + *

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); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java index 5feaf5d7..e18b89e8 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPlatformAutoConfiguration.java @@ -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. + * + *

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. * *

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. - * - *

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. - * - *

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. - * - *

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( - GraphQlClientPolicy clientPolicy, ObjectProvider 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 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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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. - * - *

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 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. - * - *

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 cache, - ObjectProvider 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. - * - *

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. - * - *

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. - * - *

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 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())); - } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPreparsedCacheConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPreparsedCacheConfiguration.java new file mode 100644 index 00000000..c633780d --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlPreparsedCacheConfiguration.java @@ -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. + * + *

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 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. + * + *

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 cache, + ObjectProvider 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 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())); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestBodyLimitConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestBodyLimitConfiguration.java new file mode 100644 index 00000000..3b3d1b23 --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestBodyLimitConfiguration.java @@ -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. + * + *

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. + * + *

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( + GraphQlClientPolicy clientPolicy, ObjectProvider 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 registration = + new FilterRegistrationBean<>(new GraphQlRequestBodyLimitFilter(path, maxBodyBytes)); + registration.setOrder(Ordered.HIGHEST_PRECEDENCE); + registration.addUrlPatterns(path); + return registration; + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestContextConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestContextConfiguration.java new file mode 100644 index 00000000..18be3a21 --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRequestContextConfiguration.java @@ -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. + * + *

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. + * + *

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. + * + *

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. + * + *

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); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java index 1be8e1dd..da79ef66 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlRootAutoConfiguration.java @@ -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 diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlScalarConfiguration.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlScalarConfiguration.java new file mode 100644 index 00000000..61cdd77a --- /dev/null +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/autoconfigure/GraphQlScalarConfiguration.java @@ -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. + * + *

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); + } +} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProvider.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProvider.java index 2cf084dd..60e6012e 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProvider.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProvider.java @@ -164,15 +164,24 @@ public final class BoundedPreparsedDocumentProvider { } } + /** + * Drops idle entries from the least-recently-accessed end and stops at the first live one. + * + *

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> 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(); } } diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpRequestEnvelope.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpRequestEnvelope.java deleted file mode 100644 index e37342c1..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlHttpRequestEnvelope.java +++ /dev/null @@ -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. - * - *

{@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 variables, - Map 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(); - } -} diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidator.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidator.java deleted file mode 100644 index 9a27234c..00000000 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidator.java +++ /dev/null @@ -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). - * - *

Everything here runs before 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. - * - *

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"); - } - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProviderTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProviderTest.java index 70a47f85..365dd669 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProviderTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/execution/BoundedPreparsedDocumentProviderTest.java @@ -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( + 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 = diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestBoundsTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestBoundsTest.java index 77b18d0a..2daf20d8 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestBoundsTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestBoundsTest.java @@ -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. * *

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 variables = new HashMap<>(); variables.put("id", null); - GraphQlHttpRequestEnvelope envelope = - new GraphQlHttpRequestEnvelope("{ q }", null, variables, Map.of()); + Map 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 listAt(GraphQlHttpRequestEnvelope envelope, String key) { - return (List) envelope.variables().get(key); + private static List listAt(Map envelope, String key) { + return (List) envelope.get(key); } @SuppressWarnings("unchecked") - private static Map objectAt(GraphQlHttpRequestEnvelope envelope, String key) { - return (Map) envelope.variables().get(key); + private static Map objectAt(Map envelope, String key) { + return (Map) 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 envelope = GraphQlJsonValues.immutableObject(variables); Map 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 envelope = GraphQlJsonValues.immutableObject(variables); filter.put("status", "CLOSED"); ids.add("b"); @@ -117,8 +93,7 @@ class GraphQlRequestBoundsTest { void theEnvelopeCopyIsUnmodifiableAllTheWayDown() { Map variables = Map.of("filter", new LinkedHashMap<>(Map.of("status", "OPEN"))); - GraphQlHttpRequestEnvelope envelope = - new GraphQlHttpRequestEnvelope("{ q }", null, variables, Map.of()); + Map envelope = GraphQlJsonValues.immutableObject(variables); Map 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(); + } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidatorTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidatorTest.java deleted file mode 100644 index 0e5595da..00000000 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/http/GraphQlRequestEnvelopeValidatorTest.java +++ /dev/null @@ -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); - } -} diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptorRequestBoundsTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptorRequestBoundsTest.java new file mode 100644 index 00000000..e84e22c7 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlPlatformWebInterceptorRequestBoundsTest.java @@ -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}. + * + *

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 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 variables = Map.of("v", "0123456789"); + + // when + Outcome outcome = intercept("{ _health }", variables, Map.of()); + + // then + assertThat(outcome.executed()).isTrue(); + } + + @Test + void aTooDeeplyNestedVariableIsRejectedAsAShapeViolation() { + // given + Map 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 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 variables, Map 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 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 variables, Map 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) {} +} diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java index 0d7e94a3..9127eba1 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfiguration.java @@ -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. * - *

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 trustedProxies) { - return new ExternalRequestUrlResolver(trustedProxies); + public ExternalRequestUrlResolver externalRequestUrlResolver() { + return new ExternalRequestUrlResolver(); } /** diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java index c59a022a..790cb015 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolver.java @@ -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. * *

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 trustedProxies; - - public ExternalRequestUrlResolver(Set 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) diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java index 8fa88076..b69acf65 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationSubmissionController.java @@ -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. * *

{@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(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); } } diff --git a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java index d05b742e..2f740842 100644 --- a/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java +++ b/src/adapter/inbound/web-notification/src/main/java/dev/caskeleton/adapter/inbound/web/notification/platform/submission/NotificationTemplateController.java @@ -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()) diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java index 3164cd29..7f2afa14 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/CallbackRequestConfigurationTest.java @@ -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 diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolverTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolverTest.java new file mode 100644 index 00000000..d81532e1 --- /dev/null +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/ExternalRequestUrlResolverTest.java @@ -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. + * + *

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; + } +} diff --git a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java index 347ab296..fc2a0c86 100644 --- a/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java +++ b/src/adapter/inbound/web-notification/src/test/java/dev/caskeleton/adapter/inbound/web/notification/platform/callback/NotificationCallbackMvcControllerTest.java @@ -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 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); diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index e4a490a4..bdbe286b 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -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, diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java index d1de21b5..8e07c90c 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAdapterAutoConfiguration.java @@ -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. * *

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. * - *

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. + *

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, diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebSecurityAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebSecurityAutoConfiguration.java new file mode 100644 index 00000000..71b42d85 --- /dev/null +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebSecurityAutoConfiguration.java @@ -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. + * + *

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. + * + *

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 {} diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java index 56a8fb85..e3435515 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/operation/DurableOperationController.java @@ -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(), diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptor.java index 7a3a0643..dd9be4c0 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptor.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptor.java @@ -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. - * - *

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 -> diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitWebConfig.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitWebConfig.java index 5712f882..35ac9aa7 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitWebConfig.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitWebConfig.java @@ -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 diff --git a/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports index 72e65cb6..2dcddba2 100644 --- a/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports +++ b/src/adapter/inbound/web/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -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 diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java index d2569c3d..1f8af93b 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebAutoConfigurationRegistrationTest.java @@ -36,6 +36,7 @@ class WebAutoConfigurationRegistrationTest { private static final List 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 diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptorTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptorTest.java index 38f0e113..1d767521 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptorTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/ratelimit/RateLimitInterceptorTest.java @@ -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() { diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java index ef393a85..121ac91a 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/ContractFixtureApplication.java @@ -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. * - *

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. + *

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 { diff --git a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java index c412075d..cd149458 100644 --- a/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java +++ b/src/adapter/inbound/web/src/testFixtures/java/dev/caskeleton/webtestkit/PipelineOrderFixtureApplication.java @@ -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 { diff --git a/src/adapter/inbound/websocket/CLAUDE.md b/src/adapter/inbound/websocket/CLAUDE.md index 67886bc3..df16edfd 100644 --- a/src/adapter/inbound/websocket/CLAUDE.md +++ b/src/adapter/inbound/websocket/CLAUDE.md @@ -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` 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. diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java index bf527436..a1561a11 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java @@ -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"); } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketAutoConfigurationTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketAutoConfigurationTest.java index dcd08263..0d6bd600 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketAutoConfigurationTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketAutoConfigurationTest.java @@ -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 diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java index 47244614..9e14be4b 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/capability/RedisCapabilityCompositionTest.java @@ -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")); } diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index 5782c5b6..94650578 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -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 diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuard.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuard.java index b84ec77f..2cbcb4c5 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuard.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuard.java @@ -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"); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunner.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunner.java index 10811b78..96c1cf55 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunner.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunner.java @@ -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 { diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java index 976a3e46..19b7d712 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/DurableOperationSubmissionOutboxIntegrationTest.java @@ -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. diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java index 76bfecc8..895c412b 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/autoconfigure/PersistenceJpaCapabilityAssemblyTest.java @@ -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(); } } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java index 5f87347c..c2d49941 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/FlywayProdSafetyValidatorTest.java @@ -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 diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java index 948df969..397c963c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/HikariPoolConstraintValidatorTest.java @@ -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"); }); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuardTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuardTest.java index 782688f3..0770903d 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuardTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaDangerousConfigurationGuardTest.java @@ -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 diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunnerTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunnerTest.java index 8585e05e..9761e124 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunnerTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/MigrationStartupRunnerTest.java @@ -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() diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java index 51daadff..6e690bf4 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/OpenInViewSafetyValidatorTest.java @@ -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")); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java index d5b2646c..5f3f9a59 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PersistenceVendorProdSafetyValidatorTest.java @@ -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); }); } diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java index efd06b45..c00a5f0d 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/PostgreSqlTransportSecurityValidatorTest.java @@ -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") diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java index 8b723a5e..be16fa9c 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/startup/RequiredEnvironmentValidatorTest.java @@ -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 diff --git a/src/adapter/outbound/support/README.md b/src/adapter/outbound/support/README.md index 0045c871..aed4bde7 100644 --- a/src/adapter/outbound/support/README.md +++ b/src/adapter/outbound/support/README.md @@ -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`와 의도적으로 구분된다.** 이쪽은 *시작* 검증(필수 어댑터/조정 빈이 꺼져 있음)이고, 후자는 비활성 옵션 어댑터에 대한 *런타임* 호출이다. diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/MigrationFailedException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/MigrationFailedException.java deleted file mode 100644 index 4464f8fb..00000000 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/MigrationFailedException.java +++ /dev/null @@ -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); - } -} diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ProfileMismatchException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ProfileMismatchException.java deleted file mode 100644 index a15eeaf4..00000000 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/ProfileMismatchException.java +++ /dev/null @@ -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); - } -} diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredAdapterDisabledException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredAdapterDisabledException.java deleted file mode 100644 index 52eee7f2..00000000 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/RequiredAdapterDisabledException.java +++ /dev/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); - } -} diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureException.java index 50cd9640..58a8a72d 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureException.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureException.java @@ -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. + * + *

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() { diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailures.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailures.java index cf4e1a69..f14c6a4f 100644 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailures.java +++ b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailures.java @@ -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}. */ diff --git a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationException.java b/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationException.java deleted file mode 100644 index f6433609..00000000 --- a/src/adapter/outbound/support/src/main/java/dev/caskeleton/adapter/outbound/support/startup/StartupValidationException.java +++ /dev/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. - * - *

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); - } -} diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureExceptionTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureExceptionTest.java index e7af1f9c..27777920 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureExceptionTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailureExceptionTest.java @@ -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); } } diff --git a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailuresTest.java b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailuresTest.java index ff862999..43b9f0c9 100644 --- a/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailuresTest.java +++ b/src/adapter/outbound/support/src/test/java/dev/caskeleton/adapter/outbound/support/startup/StartupFailuresTest.java @@ -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); diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index 8a8e4b65..f13b5a16 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -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//` 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 diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 99171cca..5f6ceacc 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -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·설정 키)은 + 두지 않는다. 두 번째 전략이 생기면 그 구현과 선택 설정을 함께 추가한다. --- diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index 0edf846c..c6116b8d 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -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 diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java index 8569a0f3..c673352e 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchRuleDiscoveryContractTest.java @@ -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", diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java index 9d0b2ab3..a1e0e9c0 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/CompositionRootBoundaryArchitectureTest.java @@ -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}. + * + *

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."); } diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java index dd043c55..a3456d33 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ForbiddenApiArchitectureTest.java @@ -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); diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java index e64ab8db..f32f513e 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java @@ -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. + * + *

{@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 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 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); } diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java index f30da0cf..a196ccde 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/fileserver/FileserverCompositionIntegrationTest.java @@ -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", diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java index a4086d1b..a325b700 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/objectstorage/ObjectStorageCompositionIntegrationTest.java @@ -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 {} diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java index ff3c3c59..febd24a4 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/integration/operation/DurableOperationCompositionIntegrationTest.java @@ -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. diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextConfig.java index 27046361..7983143b 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextConfig.java @@ -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(); } } diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextSettings.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextSettings.java deleted file mode 100644 index 163cdd74..00000000 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/concurrency/DomainContextSettings.java +++ /dev/null @@ -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; - } - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncContextTaskDecoratorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncContextTaskDecoratorTest.java index 3bdff88b..2e10197a 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncContextTaskDecoratorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncContextTaskDecoratorTest.java @@ -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 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 diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExceptionPropagationTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExceptionPropagationTest.java index bf2f4b8b..db4d4a21 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExceptionPropagationTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExceptionPropagationTest.java @@ -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( diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfigTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfigTest.java index 7be0de43..4c5b98f0 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfigTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfigTest.java @@ -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(); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java index 2dcc6cd8..0ed588d3 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncExecutorSettingsTest.java @@ -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"); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncGracefulShutdownBehaviorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncGracefulShutdownBehaviorTest.java index 5a83a033..00594d87 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncGracefulShutdownBehaviorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/async/AsyncGracefulShutdownBehaviorTest.java @@ -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(); } } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java index e0f99a40..d77fadfc 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/idempotency/IdempotencySettingsTest.java @@ -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"); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java index ff033836..bcb083c3 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/outbox/OutboxSettingsTest.java @@ -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"); } } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java index 36affa62..2b506e14 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingActivationContextTest.java @@ -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 {} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java index 48d343ea..a3287da4 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/autoconfigure/tracing/TracingSettingsTest.java @@ -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 ---- diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java index 7773fd22..e0de7791 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ActuatorSecurityHttpTest.java @@ -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 {} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java index a52cc4e7..835f4067 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ConfigurationNamespaceContractTest.java @@ -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. " diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java index b2fac644..1293e0a7 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DistributedTracingContractTest.java @@ -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"); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java index 351150a3..91203bfe 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/ErrorDetailExposureSafetyValidatorTest.java @@ -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); }); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java index 7e173d7a..64ed2c4b 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/OperationalContractRuntimeTest.java @@ -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 }) diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java index d613b4c9..0b82be3b 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/RuntimeNumericBoundsValidatorTest.java @@ -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"); }); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java index edd7fbdc..5b806aa8 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java @@ -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"); }); } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java index 65692d0b..71bbca30 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/StartupSafetyValidatorTest.java @@ -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 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; } diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java index d823f8db..652bc84f 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/startup/StartupFailureExceptionReporterTest.java @@ -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); diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java index 3a5c6cce..68446003 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/OperationCommand.java @@ -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 diff --git a/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java b/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java index 52f143dc..60797e8d 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCase.java @@ -8,6 +8,7 @@ import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.usecase.CommandUseCase; import java.time.Clock; import java.util.Objects; @@ -50,7 +51,8 @@ import java.util.Objects; // class cannot be proxied — so the gate would be declared and never applied. // RequiresPermissionProxyabilityTest // enforces this, which is the only reason the omission is not a silent one. -public class SubmitDurableOperationUseCase { +public class SubmitDurableOperationUseCase + implements CommandUseCase { private final DurableOperationStorePort operations; private final LegacyOutboxAppendPort outbox; @@ -82,7 +84,8 @@ public class SubmitDurableOperationUseCase { * @param command what to run * @return what to tell the caller */ - public OperationAcceptance submit(OperationCommand command) { + @Override + public OperationAcceptance handle(OperationCommand command) { Objects.requireNonNull(command, "command"); return transactions.inWrite( () -> { diff --git a/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java b/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java index f333d717..b0e624f8 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/operation/SubmitDurableOperationUseCaseTest.java @@ -8,6 +8,7 @@ import dev.caskeleton.application.operation.testkit.InMemoryDurableOperationStor import dev.caskeleton.application.outbox.LegacyOutboxAppendPort; import dev.caskeleton.application.outbox.NewOutboxEvent; import dev.caskeleton.application.transaction.TransactionPort; +import dev.caskeleton.application.usecase.CommandUseCase; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -37,7 +38,7 @@ class SubmitDurableOperationUseCaseTest { private final RecordingOutbox outbox = new RecordingOutbox(insideTransaction); private final RollbackAwareTransactions transactions = new RollbackAwareTransactions(operations, outbox, insideTransaction); - private final SubmitDurableOperationUseCase useCase = + private final CommandUseCase useCase = new SubmitDurableOperationUseCase( operations, outbox, transactions, Clock.fixed(NOW, ZoneOffset.UTC)); @@ -56,7 +57,7 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("an accepted submission writes both the operation and the outbox event") void submissionWritesBoth() { - OperationAcceptance acceptance = useCase.submit(command(ID, "a".repeat(64))); + OperationAcceptance acceptance = useCase.handle(command(ID, "a".repeat(64))); assertThat(acceptance.operationId()).isEqualTo(ID); assertThat(acceptance.alreadyAccepted()).isFalse(); @@ -67,7 +68,7 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("both writes happen inside one transaction") void bothWritesShareOneTransaction() { - useCase.submit(command(ID, "a".repeat(64))); + useCase.handle(command(ID, "a".repeat(64))); // Not an implementation detail. Outside one transaction the two writes can commit // independently, and every failure mode this use case exists to prevent comes back. @@ -81,7 +82,7 @@ class SubmitDurableOperationUseCaseTest { void rollbackLeavesNothing() { outbox.failNext = true; - assertThatThrownBy(() -> useCase.submit(command(ID, "a".repeat(64)))) + assertThatThrownBy(() -> useCase.handle(command(ID, "a".repeat(64)))) .isInstanceOf(IllegalStateException.class); assertThat(operations.size()).isZero(); @@ -91,10 +92,10 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("an identical resubmission returns the first operation and publishes nothing new") void resubmissionReusesTheFirstOperation() { - useCase.submit(command(ID, "a".repeat(64))); + useCase.handle(command(ID, "a".repeat(64))); OperationAcceptance repeat = - useCase.submit(command(new DurableOperationId("op-2"), "a".repeat(64))); + useCase.handle(command(new DurableOperationId("op-2"), "a".repeat(64))); // The client is pointed at the work that is actually running. Starting a second operation // would run the same report twice and hand back an id for the copy. @@ -107,10 +108,10 @@ class SubmitDurableOperationUseCaseTest { @Test void retryUnderTheSameOperationIdAppendsTheOutboxEventOnlyOnce() { // given - useCase.submit(command(ID, "a".repeat(64))); + useCase.handle(command(ID, "a".repeat(64))); // when - OperationAcceptance retry = useCase.submit(command(ID, "a".repeat(64))); + OperationAcceptance retry = useCase.handle(command(ID, "a".repeat(64))); // then assertThat(List.of(retry.alreadyAccepted(), outbox.appended.size())).containsExactly(true, 1); @@ -119,10 +120,10 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("a different request under the same principal is a different operation") void differentRequestsAreDifferentOperations() { - useCase.submit(command(ID, "a".repeat(64))); + useCase.handle(command(ID, "a".repeat(64))); OperationAcceptance second = - useCase.submit(command(new DurableOperationId("op-2"), "b".repeat(64))); + useCase.handle(command(new DurableOperationId("op-2"), "b".repeat(64))); assertThat(second.alreadyAccepted()).isFalse(); assertThat(operations.size()).isEqualTo(2); @@ -132,7 +133,7 @@ class SubmitDurableOperationUseCaseTest { @Test @DisplayName("the outbox event carries the operation id as its routing key and dedup key") void outboxEventIsAnchoredToTheOperation() { - useCase.submit(command(ID, "a".repeat(64))); + useCase.handle(command(ID, "a".repeat(64))); NewOutboxEvent event = outbox.appended.get(0); diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java index b38eedb3..b610ef54 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCase.java @@ -25,12 +25,14 @@ import dev.caskeleton.application.notification.platform.port.in.SubmitNotificati import dev.caskeleton.application.notification.platform.port.in.SubmitNotificationUseCase; import dev.caskeleton.application.notification.platform.security.ContactPointProtector; import dev.caskeleton.application.notification.platform.security.ProtectedContactPoint; +import dev.caskeleton.application.notification.platform.template.NotificationTemplateVersion; import dev.caskeleton.application.security.RequiresPermission; import dev.caskeleton.application.transaction.TransactionMode; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; import java.time.Instant; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -74,6 +76,7 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU new CanonicalNotificationPlanEncoder(); private final TransactionPort transactions; private final Clock clock; + private final Locale defaultLocale; /** * Creates the use case. @@ -86,6 +89,8 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU * @param fingerprints stable SHA-256 fingerprinting over the canonical notification plan * @param transactions the write boundary this use case owns for registration * @param clock the time source for registration timestamps + * @param defaultLocale the locale a command that names none is rendered in; a deployment setting + * rather than the host JVM's default, so the same request renders the same on every node */ public AcceptNotificationApplicationUseCase( SubmitNotificationUseCase submit, @@ -95,7 +100,8 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU NotificationIdGeneratorPort ids, RequestFingerprint fingerprints, TransactionPort transactions, - Clock clock) { + Clock clock, + Locale defaultLocale) { this.submit = Objects.requireNonNull(submit, "submit"); this.contactPoints = Objects.requireNonNull(contactPoints, "contactPoints"); this.protector = Objects.requireNonNull(protector, "protector"); @@ -108,6 +114,10 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU this.fingerprints = Objects.requireNonNull(fingerprints, "fingerprints"); this.transactions = Objects.requireNonNull(transactions, "transactions"); this.clock = Objects.requireNonNull(clock, "clock"); + this.defaultLocale = Objects.requireNonNull(defaultLocale, "defaultLocale"); + if (defaultLocale.equals(Locale.ROOT)) { + throw new IllegalArgumentException("defaultLocale must name a language"); + } } @Override @@ -118,6 +128,11 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU ContactPointValue value = parse(command.channel(), command.address()); ContactPointId contactPointId = registerOrReuse(tenantId, command.recipientRef(), value); + TemplateSelection template = + new TemplateSelection( + command.templateId(), + command.templateVersion().orElse(NotificationTemplateVersion.FIRST_VERSION), + command.locale().orElse(defaultLocale)); CorrelationId correlationId = new CorrelationId(ids.nextId().toString()); IdempotencyKey idempotencyKey = command @@ -128,6 +143,7 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU NotificationPlan provisional = plan( command, + template, tenantId, contactPointId, DERIVED_KEY_PLACEHOLDER, @@ -135,7 +151,8 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU return new IdempotencyKey(fingerprints.of(planEncoder.encode(provisional))); }); - NotificationPlan plan = plan(command, tenantId, contactPointId, idempotencyKey, correlationId); + NotificationPlan plan = + plan(command, template, tenantId, contactPointId, idempotencyKey, correlationId); return submit.handle(new SubmitNotificationCommand(plan)); } @@ -188,6 +205,7 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU */ private static NotificationPlan plan( AcceptNotificationCommand command, + TemplateSelection template, TenantId tenantId, ContactPointId contactPointId, IdempotencyKey idempotencyKey, @@ -196,12 +214,12 @@ public class AcceptNotificationApplicationUseCase implements AcceptNotificationU tenantId, idempotencyKey, command.category(), - new TemplateSelection(command.templateId(), command.templateVersion(), command.locale()), + template, command.variables(), List.of( new RecipientSpec( command.recipientRef(), - Optional.of(command.locale()), + Optional.of(template.locale()), Optional.empty(), List.of(new ContactPointSelector(command.channel(), contactPointId)), Optional.empty())), diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java index ae0dcc5b..f472aa3a 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCase.java @@ -79,7 +79,7 @@ public class PublishNotificationTemplateApplicationUseCase NotificationTemplateVersion version = new NotificationTemplateVersion( command.templateId(), - command.version(), + command.version().orElse(NotificationTemplateVersion.FIRST_VERSION), command.channel(), command.locale(), command.fallbackLocale(), diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/AcceptNotificationCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/AcceptNotificationCommand.java index 228e90c1..9e0ee759 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/AcceptNotificationCommand.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/AcceptNotificationCommand.java @@ -39,8 +39,8 @@ public record AcceptNotificationCommand( Channel channel, String address, String templateId, - long templateVersion, - Locale locale, + Optional templateVersion, + Optional locale, Map variables, Optional idempotencyKey, String category) @@ -49,6 +49,7 @@ public record AcceptNotificationCommand( public AcceptNotificationCommand { Objects.requireNonNull(tenantId, "tenantId"); Objects.requireNonNull(channel, "channel"); + Objects.requireNonNull(templateVersion, "templateVersion"); Objects.requireNonNull(locale, "locale"); Objects.requireNonNull(idempotencyKey, "idempotencyKey"); variables = Map.copyOf(Objects.requireNonNull(variables, "variables")); @@ -64,7 +65,7 @@ public record AcceptNotificationCommand( if (templateId == null || templateId.isBlank()) { throw new IllegalArgumentException("templateId"); } - if (templateVersion <= 0) { + if (templateVersion.filter(version -> version <= 0).isPresent()) { throw new IllegalArgumentException("templateVersion"); } if (category == null || category.isBlank()) { diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/PublishNotificationTemplateCommand.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/PublishNotificationTemplateCommand.java index e5d03bfc..ae02ae51 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/PublishNotificationTemplateCommand.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/port/in/PublishNotificationTemplateCommand.java @@ -27,7 +27,7 @@ import java.util.Set; */ public record PublishNotificationTemplateCommand( String templateId, - long version, + Optional version, Channel channel, Locale locale, Optional fallbackLocale, @@ -38,6 +38,7 @@ public record PublishNotificationTemplateCommand( public PublishNotificationTemplateCommand { Objects.requireNonNull(templateId, "templateId"); + Objects.requireNonNull(version, "version"); Objects.requireNonNull(channel, "channel"); Objects.requireNonNull(locale, "locale"); Objects.requireNonNull(fallbackLocale, "fallbackLocale"); @@ -48,7 +49,7 @@ public record PublishNotificationTemplateCommand( if (templateId.isBlank()) { throw new IllegalArgumentException("templateId"); } - if (version <= 0) { + if (version.filter(value -> value <= 0).isPresent()) { throw new IllegalArgumentException("version"); } if (slots.isEmpty()) { diff --git a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateVersion.java b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateVersion.java index 7c49ff36..78f5521b 100644 --- a/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateVersion.java +++ b/src/application-notification/src/main/java/dev/caskeleton/application/notification/platform/template/NotificationTemplateVersion.java @@ -17,6 +17,12 @@ public record NotificationTemplateVersion( TemplateStatus status, String contentDigest) { + /** + * The version a submission or a publication that names none refers to: the first one. A default + * the application owns, so every transport means the same thing by an omitted version. + */ + public static final long FIRST_VERSION = 1L; + public NotificationTemplateVersion { Objects.requireNonNull(templateId, "templateId"); Objects.requireNonNull(channel, "channel"); diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java index 6fc2a5c2..d616e393 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/AcceptNotificationApplicationUseCaseTest.java @@ -33,6 +33,7 @@ import org.junit.jupiter.api.Test; class AcceptNotificationApplicationUseCaseTest { private static final Instant NOW = Instant.parse("2026-09-19T00:00:00Z"); + private static final Locale DEFAULT_LOCALE = Locale.forLanguageTag("ko-KR"); @Test void derivedIdempotencyKeyIsStableSha256OverTheCanonicalPlan() { @@ -49,7 +50,8 @@ class AcceptNotificationApplicationUseCaseTest { ids, PlatformFakes.fingerprints(), new PlatformFakes.RecordingTransactions(), - Clock.fixed(NOW, ZoneOffset.UTC)); + Clock.fixed(NOW, ZoneOffset.UTC), + DEFAULT_LOCALE); AcceptNotificationCommand command = command(Map.of("amount", new NotificationVariable.TextValue("10"))); @@ -81,7 +83,8 @@ class AcceptNotificationApplicationUseCaseTest { ids, PlatformFakes.fingerprints(), new PlatformFakes.RecordingTransactions(), - Clock.fixed(NOW, ZoneOffset.UTC)); + Clock.fixed(NOW, ZoneOffset.UTC), + DEFAULT_LOCALE); Map first = new LinkedHashMap<>(); first.put("amount", new NotificationVariable.TextValue("10")); @@ -109,8 +112,8 @@ class AcceptNotificationApplicationUseCaseTest { Channel.EMAIL, "person@example.com", "payment-receipt", - 1, - Locale.KOREAN, + Optional.of(1L), + Optional.of(Locale.KOREAN), Map.of(), Optional.empty(), null)); @@ -119,6 +122,69 @@ class AcceptNotificationApplicationUseCaseTest { assertThat(thrown).isInstanceOf(IllegalArgumentException.class).hasMessage("category"); } + @Test + void aCommandNamingNoVersionOrLocaleGetsTheFirstVersionAndTheConfiguredLocale() { + // given + CapturingSubmit submit = new CapturingSubmit(); + AcceptNotificationApplicationUseCase useCase = + new AcceptNotificationApplicationUseCase( + submit, + new InMemoryContactPoints(), + protector(), + PlatformFakes.tenant("tenant-a"), + new PlatformFakes.SequentialIds(), + PlatformFakes.fingerprints(), + new PlatformFakes.RecordingTransactions(), + Clock.fixed(NOW, ZoneOffset.UTC), + DEFAULT_LOCALE); + AcceptNotificationCommand command = + new AcceptNotificationCommand( + Optional.empty(), + "customer-42", + Channel.EMAIL, + "person@example.com", + "payment-receipt", + Optional.empty(), + Optional.empty(), + Map.of(), + Optional.empty(), + "billing"); + + // when + useCase.handle(command); + + // then + assertThat(submit.plans.getFirst()) + .extracting( + plan -> plan.template().version(), + plan -> plan.template().locale(), + plan -> plan.recipients().getFirst().locale()) + .containsExactly(1L, DEFAULT_LOCALE, Optional.of(DEFAULT_LOCALE)); + } + + @Test + void theRootLocaleIsRefusedAsTheConfiguredDefault() { + // when + Throwable thrown = + catchThrowable( + () -> + new AcceptNotificationApplicationUseCase( + new CapturingSubmit(), + new InMemoryContactPoints(), + protector(), + PlatformFakes.tenant("tenant-a"), + new PlatformFakes.SequentialIds(), + PlatformFakes.fingerprints(), + new PlatformFakes.RecordingTransactions(), + Clock.fixed(NOW, ZoneOffset.UTC), + Locale.ROOT)); + + // then + assertThat(thrown) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("defaultLocale must name a language"); + } + private static AcceptNotificationCommand command(Map variables) { return new AcceptNotificationCommand( Optional.empty(), @@ -126,8 +192,8 @@ class AcceptNotificationApplicationUseCaseTest { Channel.EMAIL, "person@example.com", "payment-receipt", - 1, - Locale.KOREAN, + Optional.of(1L), + Optional.of(Locale.KOREAN), variables, Optional.empty(), "billing"); diff --git a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java index 07cac2dc..3266d42a 100644 --- a/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java +++ b/src/application-notification/src/test/java/dev/caskeleton/application/notification/platform/dispatch/PublishNotificationTemplateApplicationUseCaseTest.java @@ -26,7 +26,7 @@ class PublishNotificationTemplateApplicationUseCaseTest { PublishNotificationTemplateCommand command = new PublishNotificationTemplateCommand( "payment-receipt", - 1L, + Optional.of(1L), Channel.EMAIL, Locale.KOREAN, Optional.empty(), @@ -41,6 +41,32 @@ class PublishNotificationTemplateApplicationUseCaseTest { assertThat(transactions.boundaries).containsExactly("WRITE"); } + @Test + void aPublicationNamingNoVersionPublishesTheFirstVersion() { + // given + PublishNotificationTemplateApplicationUseCase useCase = + new PublishNotificationTemplateApplicationUseCase( + new RecordingTemplates(), + PublishNotificationTemplateApplicationUseCaseTest::sha256, + new PlatformFakes.RecordingTransactions()); + PublishNotificationTemplateCommand command = + new PublishNotificationTemplateCommand( + "payment-receipt", + Optional.empty(), + Channel.EMAIL, + Locale.KOREAN, + Optional.empty(), + Map.of(TemplateSlot.TEXT_BODY, "금액 {amount}"), + Set.of("amount"), + Set.of()); + + // when + NotificationTemplateVersion published = useCase.handle(command); + + // then + assertThat(published.version()).isEqualTo(NotificationTemplateVersion.FIRST_VERSION); + } + private static byte[] sha256(byte[] bytes) { try { return java.security.MessageDigest.getInstance("SHA-256").digest(bytes); diff --git a/src/composition/notification-platform/README.md b/src/composition/notification-platform/README.md index 20406073..a2bd3106 100644 --- a/src/composition/notification-platform/README.md +++ b/src/composition/notification-platform/README.md @@ -56,7 +56,7 @@ runtimeOnly project(':composition:notification-platform') // 알림 | 항상 (키 7종과 각 키 id, 32바이트 이상 base64, 서로 달라야 함) | `APP_NOTIFICATION_PLATFORM_{CONTACT_ENCRYPTION,CONTACT_LOOKUP_HMAC,CALLBACK_SIGNING,PROVIDER_CREDENTIAL,PAYLOAD_ENCRYPTION,PROVIDER_REQUEST_LOOKUP_HMAC,CALLBACK_FINGERPRINT_HMAC}_KEY`, 같은 이름 + `_ID` | | SMTP provider | `APP_NOTIFICATION_PLATFORM_SMTP_ENABLED=true`, `APP_NOTIFICATION_PLATFORM_SMTP_SENDER_IDENTITY`, `SPRING_MAIL_HOST`, `SPRING_MAIL_PORT`, `SPRING_MAIL_USERNAME`, `SPRING_MAIL_PASSWORD` | | SES provider | `APP_NOTIFICATION_PLATFORM_SES_ENABLED=true`, `APP_NOTIFICATION_PLATFORM_SES_SENDER_IDENTITY`, `APP_NOTIFICATION_PLATFORM_SES_ACCESS_KEY_ID`, `APP_NOTIFICATION_PLATFORM_SES_CREDENTIAL_KEY_ID`, `APP_NOTIFICATION_PLATFORM_SES_REGION` | -| provider 콜백 | `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED=true`, SES는 `APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, 프록시 뒤라면 `APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES` | +| provider 콜백 | `APP_NOTIFICATION_PLATFORM_CALLBACKS_ENABLED=true`, SES는 `APP_NOTIFICATION_PLATFORM_SES_ALLOWED_TOPIC_ARNS`, 프록시 뒤라면 `APP_SERVER_FORWARD_HEADERS_STRATEGY=native` + `server.tomcat.remoteip.internal-proxies`(콜백 전용 프록시 목록은 없다) | 나머지(발송 배치 크기, lease, 준비 상태 임계값 등)는 기본값으로 동작한다. 설명은 `docs/notification/configuration-reference.md`. diff --git a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java index e22db47d..f1b35282 100644 --- a/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java +++ b/src/composition/notification-platform/src/main/java/dev/caskeleton/composition/notification/NotificationSubmissionConfiguration.java @@ -28,6 +28,8 @@ import dev.caskeleton.application.notification.platform.security.ContactPointPro import dev.caskeleton.application.notification.platform.template.TemplateRegistry; import dev.caskeleton.application.transaction.TransactionPort; import java.time.Clock; +import java.util.Locale; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -86,9 +88,18 @@ class NotificationSubmissionConfiguration { NotificationIdGeneratorPort ids, RequestFingerprint fingerprints, TransactionPort transactions, - Clock clock) { + Clock clock, + @Value("${ca-skeleton.notification.platform.default-locale:ko-KR}") String defaultLocale) { return new AcceptNotificationApplicationUseCase( - submit, contactPoints, protector, tenants, ids, fingerprints, transactions, clock); + submit, + contactPoints, + protector, + tenants, + ids, + fingerprints, + transactions, + clock, + Locale.forLanguageTag(defaultLocale.trim())); } /** diff --git a/src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml b/src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml index 9fd05a9f..3e2e94b2 100644 --- a/src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml +++ b/src/composition/notification-platform/src/main/resources/config/module-defaults/notification.yml @@ -28,6 +28,9 @@ ca-skeleton: # SERVING | INGEST_ONLY. SERVING refuses to start without a working provider; INGEST_ONLY # stores requests and does not dispatch, which is the shape a migration or a drain wants. mode: ${APP_NOTIFICATION_PLATFORM_MODE:SERVING} + # BCP 47 tag a submission that names no locale is rendered in. A deployment setting rather + # than the host JVM's default, so the same request renders the same on every node. + default-locale: ${APP_NOTIFICATION_PLATFORM_DEFAULT_LOCALE:ko-KR} dispatch: claim-batch-size: ${APP_NOTIFICATION_PLATFORM_CLAIM_BATCH_SIZE:50} # The lease must outlast a provider call plus its timeout, or a live worker's delivery is @@ -59,12 +62,9 @@ ca-skeleton: # is refused at binding rather than at the database, after the callback was acknowledged. max-body-bytes: ${APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES:65508} replay-skew: ${APP_NOTIFICATION_PLATFORM_CALLBACK_REPLAY_SKEW:5m} - # Peers whose Forwarded/X-Forwarded-* headers may be believed when reconstructing the URL a - # provider signed. Empty by default, and that is the safe default rather than the convenient - # one: with no entry the resolver uses what the container observed, so no caller can choose - # the URL its own signature is checked against. A deployment behind a load balancer lists its - # proxies here. - trusted-proxies: ${APP_NOTIFICATION_PLATFORM_CALLBACK_TRUSTED_PROXIES:} + # The URL a provider signed is rebuilt from what the container reports. Behind a load + # balancer set APP_SERVER_FORWARD_HEADERS_STRATEGY=native and name the proxies in + # server.tomcat.remoteip.internal-proxies; there is no callback-specific proxy list. # Provider profiles, keyed by profile id. None by default: an empty map with mode=SERVING is # refused at startup, which is the intended outcome for "enabled but not configured". # diff --git a/src/sample-portfolio/README.md b/src/sample-portfolio/README.md index 1ecb7c35..e52abe8c 100644 --- a/src/sample-portfolio/README.md +++ b/src/sample-portfolio/README.md @@ -403,17 +403,21 @@ curl -X POST localhost:8080/work-logs -H 'Content-Type: application/json' -d '{ - 관계형 저장소는 다른 서비스와 똑같이 고른다: `build.gradle`의 `implementation project(':adapter:outbound:persistence-jpa')` 한 줄과 그 모듈의 auto-configuration. (`implementation`인 이유는 샘플 어댑터가 모듈의 `AuditableEntity`·`AuditContextPort`를 직접 쓰기 - 때문이다.) 그래서 컴포넌트 스캔은 persistence 패키지를 부르지 않는다 — 샘플(`dev.caskeleton.sample`)과 - 이 lean 앱이 아직 스캔으로 배선하는 web·identifier·objectstorage·core 계약 패키지만 나열한다. - JPA가 두 번 들어오거나, 모듈의 기동 가드 없이 들어오는 일이 없다. + 때문이다.) 컴포넌트 스캔과 `@ConfigurationPropertiesScan`은 샘플 패키지(`dev.caskeleton.sample`) + 하나만 본다. web·objectstorage는 자기 `AutoConfiguration.imports`로, identifier는 샘플 config가 + 직접 만드는 타입으로 들어온다. 그래서 JPA가 두 번 들어오거나 모듈의 기동 가드 없이 들어오는 일이 + 없고, web leaf에 새 컨트롤러가 생겨도 샘플에 끌려오지 않는다(Wave 2 때 web 스캔이 durable operation + 엔드포인트를 샘플에 등록한 적이 있다). - **`@SpringBootApplication` 대신 `@Configuration` + `@EnableAutoConfiguration` + `@ComponentScan` 을 쓴 이유**: `@SpringBootApplication` 은 `@SpringBootConfiguration` 을 포함하는데, 그러면 이 클래스가 Spring Boot 의 `AnnotatedClassFinder` 에 보입니다. 그 finder 가 이 클래스와 (같은 패키지·테스트 classpath 의) `SamplePortfolioTestApplication` **둘 다** 찾으면 "multiple @SpringBootConfiguration" 오류를 냅니다. `@Configuration`(= `@SpringBootConfiguration` 아님)을 쓰면 finder 에 숨으면서도, `@SpringBootTest(classes = SamplePortfolioApplication.class)` 로 부팅하는 데는 문제가 없습니다. -- **`@ComponentScan` 의 exclude**: `SecurityConfig`·`MethodSecurityConfig` — 공개 데모 앱이라 IdP나 - 메서드 보안 principal 없이 URL에 접근해야 한다. 프로덕션 모듈은 이 가드를 유지한다. +- **`@EnableAutoConfiguration(exclude = WebSecurityAutoConfiguration.class)`**: web leaf의 보안 root + (JWT 필터 체인·메서드 보안·권한 port)만 뺀다 — 공개 데모 앱이라 IdP나 메서드 보안 principal 없이 + URL에 접근해야 하고, 그 자리는 `SamplePublicAccessSecurityConfig`가 채운다. 에러 envelope·필터· + health·rate limit은 `WebAdapterAutoConfiguration`으로 프로덕션과 같게 들어온다. - 데이터 계층을 빼고 뜨는 테스트 슬라이스(`DataSourceAutoConfiguration` 제외)는 `ca-skeleton.persistence-jpa.enabled=false`도 함께 준다. 모듈은 classpath에 있으면 켜지기 때문이다. diff --git a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java index d4c19dfe..2e2f5903 100644 --- a/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java +++ b/src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapterIntegrationTest.java @@ -48,6 +48,7 @@ import org.testcontainers.postgresql.PostgreSQLContainer; @Import({ JpaConfig.class, PosterRepositoryAdapter.class, + PosterImageAttachmentCasRepository.class, PosterRepositoryAdapterIntegrationTest.TestAuditConfig.class }) @TestPropertySource( @@ -62,11 +63,11 @@ class PosterRepositoryAdapterIntegrationTest { static final PostgreSQLContainer POSTGRES = PostgreSqlTestContainer.create(); private static final PosterId ID = PosterId.of("0190bd6e-7c3e-7abc-8def-0123456789ab"); - private static final String IMAGE_KEY = "posters/" + ID.value() + "/image"; private static final PosterImageReference REFERENCE = PosterImageReference.of("osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"); @Autowired PosterRepositoryAdapter adapter; + @Autowired PosterImageAttachmentCasRepository attachments; @Autowired TestEntityManager em; @Test @@ -99,7 +100,7 @@ class PosterRepositoryAdapterIntegrationTest { // given saveAndDetach(sample()); Poster loaded = adapter.findById(ID).orElseThrow(); - loaded.attachImage(IMAGE_KEY); + loaded.attachPublishedImage(REFERENCE); loaded.publish(); // when @@ -108,8 +109,8 @@ class PosterRepositoryAdapterIntegrationTest { // then assertThat(adapter.findById(ID)) .get() - .extracting(Poster::status, Poster::imageKey) - .containsExactly(PosterStatus.PUBLISHED, IMAGE_KEY); + .extracting(Poster::status, Poster::imageReference) + .containsExactly(PosterStatus.PUBLISHED, REFERENCE.value()); } @Test @@ -176,6 +177,56 @@ class PosterRepositoryAdapterIntegrationTest { assertThat(exists).isEqualTo(expected); } + @Test + void aPreV8RawKeyRowReadsBackWithoutAnImage() { + // given + insertPreV8RowWithRawKey(); + + // when + Optional found = adapter.findById(ID); + + // then + assertThat(found).get().extracting(Poster::hasImage).isEqualTo(false); + } + + @Test + void canonicalAttachClearsAPreV8RawKeyOnTheSameRow() { + // given + insertPreV8RowWithRawKey(); + + // when + attachments.attach(ID, 0L, REFERENCE, Instant.parse("2026-06-15T00:00:00Z")); + + // then + em.clear(); + assertThat( + (Object[]) + em.getEntityManager() + .createNativeQuery( + "select image_key, image_reference from poster where id = :id") + .setParameter("id", UUID.fromString(ID.value())) + .getSingleResult()) + .containsExactly(null, REFERENCE.value()); + } + + /** A row as the removed legacy upload mode left it: raw {@code image_key}, no reference. */ + private void insertPreV8RowWithRawKey() { + em.getEntityManager() + .createNativeQuery( + """ + insert into poster ( + id, title, caption, image_key, status, version, + created_at, updated_at, created_by, updated_by + ) values ( + :id, 'legacy', 'legacy', 'posters/legacy/image', 'DRAFT', 0, + now(), now(), 'old-binary', 'old-binary' + ) + """) + .setParameter("id", UUID.fromString(ID.value())) + .executeUpdate(); + em.clear(); + } + private static Poster sample() { return Poster.create(ID, "여름 세일 배너", "7월 한정"); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java index 0dff8cfe..152936c4 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/SamplePortfolioApplication.java @@ -1,68 +1,36 @@ package dev.caskeleton.sample.portfolio; -import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig; -import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; -import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; -import dev.caskeleton.adapter.inbound.web.operation.DurableOperationController; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; /** * Standalone composition root for the WorkLog sample/reference application. Disposable: deleting * the {@code sample-portfolio} module removes it without affecting production. * - *

Relational persistence is selected the way any application selects a capability: the build - * depends on {@code adapter:outbound:persistence-jpa}, and the module's own auto-configuration - * assembles it. The scan therefore names the sample and the modules this lean app still wires by - * scanning — web, identifier, object storage and the core contracts — and never the persistence - * package, so JPA cannot arrive twice or without its startup policy. + *

Every module this app uses arrives the way it arrives in any application: through its own + * auto-configuration, because the build depends on it. The scan covers the sample's own package and + * nothing else — web, persistence, object storage and identifier are never scanned, so a new + * controller or configuration added to one of those leaves cannot land in the sample by accident (a + * scan of the web leaf once registered the durable operation endpoint here, with none of the store + * it needs). * - *

See README for the wiring rationale: why {@code @Configuration} is used instead of - * {@code @SpringBootApplication}, why the two security exclusions exist, and the lean-bootstrap - * omissions a full clone would add. + *

The one exclusion is the web leaf's security root: the sample is a public demo app with its + * own permit-all chain ({@code SamplePublicAccessSecurityConfig}), so URL access does not require a + * configured IdP or a method-security principal. The rest of the web adapter — error envelope, + * filters, health endpoint, rate limiting — comes from {@code WebAdapterAutoConfiguration} as in + * production. + * + *

See README for why {@code @Configuration} is used instead of {@code @SpringBootApplication} + * and the lean-bootstrap omissions a full clone would add. */ @Configuration -// The web leaf's own root would bring the production security back; this app scans that leaf -// itself instead, minus the two security configurations below. -@EnableAutoConfiguration(exclude = WebAdapterAutoConfiguration.class) -@ComponentScan( - basePackages = { - "dev.caskeleton.sample", - "dev.caskeleton.adapter.inbound.web", - "dev.caskeleton.adapter.outbound.identifier", - "dev.caskeleton.adapter.outbound.objectstorage", - "dev.caskeleton.application", - "dev.caskeleton.domain", - "dev.caskeleton.shared" - }, - excludeFilters = { - // The standalone sample is a public demo app: URL access should not require a configured - // IdP or method-security principal. Production modules keep these guards. The durable - // operation endpoint is imported by its own auto-configuration only when the JPA store and - // outbox are there; the sample wires neither, so a scan must not register it. - @ComponentScan.Filter( - type = FilterType.ASSIGNABLE_TYPE, - classes = { - SecurityConfig.class, - MethodSecurityConfig.class, - WebAdapterAutoConfiguration.class, - DurableOperationController.class - }) - }) -@ConfigurationPropertiesScan( - basePackages = { - "dev.caskeleton.sample", - "dev.caskeleton.adapter.inbound.web", - "dev.caskeleton.adapter.outbound.identifier", - "dev.caskeleton.adapter.outbound.objectstorage", - "dev.caskeleton.application", - "dev.caskeleton.domain", - "dev.caskeleton.shared" - }) +@EnableAutoConfiguration(exclude = WebSecurityAutoConfiguration.class) +@ComponentScan("dev.caskeleton.sample") +@ConfigurationPropertiesScan("dev.caskeleton.sample") public class SamplePortfolioApplication { public static void main(String[] args) { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterController.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterController.java index 8cdf94fe..27ede6c3 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterController.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterController.java @@ -2,8 +2,6 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; import dev.caskeleton.adapter.inbound.web.pagination.PageParams; -import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; -import dev.caskeleton.adapter.inbound.web.pagination.SortParam; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.CreatePosterRequest; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.UpdatePosterRequest; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.PosterResponse; @@ -29,8 +27,7 @@ import dev.caskeleton.shared.response.PageMeta; import dev.caskeleton.shared.response.ResponseMeta; import jakarta.validation.Valid; import java.util.List; -import java.util.Locale; -import java.util.UUID; +import java.util.Optional; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; @@ -88,21 +85,11 @@ public class PosterController { @RequestParam(required = false) PosterStatus status) { PageParams pageParams = PageParams.of(page, size); - PosterSortField sortField = null; - boolean ascending = true; - String appliedSort = null; - if (sort != null && !sort.isBlank()) { - SortParam parsed = SortParam.parse(sort); // rejects non-native syntax → 400 - sortField = PosterSortField.fromRequest(parsed.field()); - if (sortField == null) { - throw new PageValidationException( - "sort", - "SORT_FIELD_NOT_ALLOWED", - "sort field '" + parsed.field() + "' is not sortable"); - } - ascending = parsed.ascending(); - appliedSort = parsed.canonical(); - } + Optional> requested = + WebRequestParams.sort(sort, PosterWebMapper.SORT_FIELDS); + PosterSortField sortField = WebRequestParams.Sort.fieldOf(requested); + boolean ascending = WebRequestParams.Sort.ascendingOf(requested); + String appliedSort = WebRequestParams.Sort.canonicalOf(requested); PosterPage result = list.handle( @@ -159,6 +146,6 @@ public class PosterController { * IllegalArgumentException} on a malformed id → HTTP 400). */ private static PosterId toId(String raw) { - return PosterId.of(UUID.fromString(raw.toLowerCase(Locale.ROOT)).toString()); + return PosterId.of(WebRequestParams.canonicalUuid(raw)); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationController.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationController.java index ee0ea3e6..a9fcc3dd 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationController.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterImagePublicationController.java @@ -19,8 +19,6 @@ import dev.caskeleton.sample.portfolio.application.poster.PublishPosterImageUseC import dev.caskeleton.sample.portfolio.application.query.GetPosterImagePublicationStatusQuery; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import java.time.Duration; -import java.util.Locale; -import java.util.UUID; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -108,6 +106,6 @@ public final class PosterImagePublicationController { } private static PosterId toId(String raw) { - return PosterId.of(UUID.fromString(raw.toLowerCase(Locale.ROOT)).toString()); + return PosterId.of(WebRequestParams.canonicalUuid(raw)); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WebRequestParams.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WebRequestParams.java new file mode 100644 index 00000000..a54df7d9 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WebRequestParams.java @@ -0,0 +1,91 @@ +package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; + +import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; +import dev.caskeleton.adapter.inbound.web.pagination.SortParam; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +/** + * The request parsing every sample controller does the same way: path ids and {@code + * ?sort=field,direction}. + * + *

The request vocabulary for sorting — which wire names select which field — belongs here, the + * web adapter, rather than to the domain enum: the domain names logical fields, the web adapter + * names what a client may type, and the persistence adapter names the column. A domain enum that + * knew the HTTP name and the persistence property at once had to change for either. + */ +final class WebRequestParams { + + private WebRequestParams() {} + + /** + * A path id as the canonical 36-character lowercase UUID. {@code UUID.fromString} is a parser + * (not a generator) and throws {@link IllegalArgumentException} on a malformed id, which the + * error handler answers with 400. + * + * @param raw the path segment + * @return the canonical form + */ + static String canonicalUuid(String raw) { + return UUID.fromString(raw.toLowerCase(Locale.ROOT)).toString(); + } + + /** + * Parses {@code ?sort=field,direction} against the fields a resource allows. + * + * @param raw the query parameter, possibly {@code null} or blank + * @param allowed wire field name → logical field; matched case-insensitively + * @param the logical field type + * @return the requested sort, or empty when the client asked for none + * @throws PageValidationException {@code SORT_FIELD_NOT_ALLOWED} for a name outside {@code + * allowed}; {@link SortParam#parse} rejects a malformed value first + */ + static Optional> sort(String raw, Map allowed) { + if (raw == null || raw.isBlank()) { + return Optional.empty(); + } + SortParam parsed = SortParam.parse(raw); + F field = lowerCased(allowed).get(parsed.field().toLowerCase(Locale.ROOT)); + if (field == null) { + throw new PageValidationException( + "sort", "SORT_FIELD_NOT_ALLOWED", "sort field '" + parsed.field() + "' is not sortable"); + } + return Optional.of(new Sort<>(field, parsed.ascending(), parsed.canonical())); + } + + private static Map lowerCased(Map allowed) { + return allowed.entrySet().stream() + .collect( + Collectors.toMap( + entry -> entry.getKey().toLowerCase(Locale.ROOT), Map.Entry::getValue)); + } + + /** + * A resolved sort request. + * + * @param field the logical field + * @param ascending the direction + * @param canonical the applied value echoed in {@code meta.page.sort} + * @param the logical field type + */ + record Sort(F field, boolean ascending, String canonical) { + + /** The logical field, or {@code null} when unsorted. */ + static F fieldOf(Optional> sort) { + return sort.map(Sort::field).orElse(null); + } + + /** The direction; ascending when unsorted. */ + static boolean ascendingOf(Optional> sort) { + return sort.map(Sort::ascending).orElse(true); + } + + /** The echoed value, or {@code null} when unsorted. */ + static String canonicalOf(Optional> sort) { + return sort.map(Sort::canonical).orElse(null); + } + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogController.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogController.java index de74a237..c32e482d 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogController.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WorkLogController.java @@ -6,8 +6,6 @@ import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedExceptio import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.adapter.inbound.web.observability.ResponseMetaFactory; import dev.caskeleton.adapter.inbound.web.pagination.PageParams; -import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; -import dev.caskeleton.adapter.inbound.web.pagination.SortParam; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.CreateWorkLogRequest; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.request.UpdateWorkLogRequest; import dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response.RepoStatsResponse; @@ -37,9 +35,8 @@ import dev.caskeleton.shared.response.ResponseMeta; import jakarta.validation.Valid; import jakarta.validation.constraints.Size; import java.util.List; -import java.util.Locale; +import java.util.Optional; import java.util.OptionalLong; -import java.util.UUID; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; @@ -97,21 +94,11 @@ public class WorkLogController { @RequestParam(required = false) WorkCategory category) { PageParams pageParams = PageParams.of(page, size); - WorkLogSortField sortField = null; - boolean ascending = true; - String appliedSort = null; - if (sort != null && !sort.isBlank()) { - SortParam parsed = SortParam.parse(sort); // rejects non-native syntax → 400 - sortField = WorkLogSortField.fromRequest(parsed.field()); - if (sortField == null) { - throw new PageValidationException( - "sort", - "SORT_FIELD_NOT_ALLOWED", - "sort field '" + parsed.field() + "' is not sortable"); - } - ascending = parsed.ascending(); - appliedSort = parsed.canonical(); - } + Optional> requested = + WebRequestParams.sort(sort, WorkLogWebMapper.SORT_FIELDS); + WorkLogSortField sortField = WebRequestParams.Sort.fieldOf(requested); + boolean ascending = WebRequestParams.Sort.ascendingOf(requested); + String appliedSort = WebRequestParams.Sort.canonicalOf(requested); WorkLogPage result = list.handle( @@ -247,6 +234,6 @@ public class WorkLogController { * IllegalArgumentException} on a malformed id → HTTP 400. See README. */ private static WorkLogId toId(String raw) { - return WorkLogId.of(UUID.fromString(raw.toLowerCase(Locale.ROOT)).toString()); + return WorkLogId.of(WebRequestParams.canonicalUuid(raw)); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/PosterResponse.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/PosterResponse.java index 89d980bd..7471dcfd 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/PosterResponse.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/dto/response/PosterResponse.java @@ -3,6 +3,9 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.dto.response; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterStatus; -/** A poster with its current state. {@code imageKey} is null until an image is uploaded. */ +/** + * A poster with its current state. {@code imageKey} keeps its wire name and carries the published + * opaque image reference; it is null until an image is published. + */ public record PosterResponse( PosterId id, String title, String caption, String imageKey, PosterStatus status) {} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/PosterWebMapper.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/PosterWebMapper.java index b72e89d5..df98f3d9 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/PosterWebMapper.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/PosterWebMapper.java @@ -7,10 +7,16 @@ import dev.caskeleton.sample.portfolio.application.command.CreatePosterCommand; import dev.caskeleton.sample.portfolio.application.command.UpdatePosterCommand; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; +import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField; +import java.util.Map; /** Translates between poster REST DTOs and application/domain types. */ public final class PosterWebMapper { + /** Wire names a client may put in {@code ?sort=} → the logical field each selects. */ + public static final Map SORT_FIELDS = + Map.of("title", PosterSortField.TITLE, "status", PosterSortField.STATUS); + private PosterWebMapper() {} public static CreatePosterCommand toCommand(CreatePosterRequest r) { @@ -24,6 +30,6 @@ public final class PosterWebMapper { } public static PosterResponse toResponse(Poster p) { - return new PosterResponse(p.id(), p.title(), p.caption(), p.imageKey(), p.status()); + return new PosterResponse(p.id(), p.title(), p.caption(), p.imageReference(), p.status()); } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/WorkLogWebMapper.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/WorkLogWebMapper.java index 294d4ff9..2f367afa 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/WorkLogWebMapper.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/mapper/WorkLogWebMapper.java @@ -10,14 +10,20 @@ import dev.caskeleton.sample.portfolio.application.command.UpdateWorkLogCommand; import dev.caskeleton.sample.portfolio.domain.worklog.RepoStats; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import dev.caskeleton.shared.error.MappingException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; +import java.util.Map; import java.util.OptionalLong; public final class WorkLogWebMapper { + /** Wire names a client may put in {@code ?sort=} → the logical field each selects. */ + public static final Map SORT_FIELDS = + Map.of("title", WorkLogSortField.TITLE, "periodStart", WorkLogSortField.PERIOD_START); + private WorkLogWebMapper() {} public static CreateWorkLogCommand toCommand(CreateWorkLogRequest r, String owner) { diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/PosterEntity.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/PosterEntity.java index 1643068e..7bfa6ac1 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/PosterEntity.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/entity/PosterEntity.java @@ -31,10 +31,8 @@ public class PosterEntity extends AuditableEntity { @Column(length = 2000) private String caption; - // Object-storage key of the uploaded image; null until an image is attached. - @Column(name = "image_key", length = 512) - private String imageKey; - + // The pre-V8 `image_key` column is left unmapped: nothing writes it, the canonical attach clears + // it, and the V8 check constraint keeps it exclusive with `image_reference`. @Column(name = "image_reference", length = 96) private String imageReference; @@ -47,27 +45,16 @@ public class PosterEntity extends AuditableEntity { protected PosterEntity() {} - public PosterEntity( - UUID id, String title, String caption, String imageKey, PosterStatus status, Long version) { - this(id, title, caption, imageKey, null, status, version); - } - public PosterEntity( UUID id, String title, String caption, - String imageKey, String imageReference, PosterStatus status, Long version) { - if (imageKey != null && imageReference != null) { - throw new IllegalArgumentException( - "poster entity cannot contain both image key and image reference"); - } this.id = id; this.title = title; this.caption = caption; - this.imageKey = imageKey; this.imageReference = imageReference; this.status = status; this.version = version; @@ -85,10 +72,6 @@ public class PosterEntity extends AuditableEntity { return caption; } - public String getImageKey() { - return imageKey; - } - public String getImageReference() { return imageReference; } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/PosterPersistenceMapper.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/PosterPersistenceMapper.java index ab7110c2..48280f38 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/PosterPersistenceMapper.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/PosterPersistenceMapper.java @@ -3,6 +3,7 @@ package dev.caskeleton.sample.portfolio.adapter.outbound.persistence.mapper; import dev.caskeleton.sample.portfolio.adapter.outbound.persistence.entity.PosterEntity; import dev.caskeleton.sample.portfolio.domain.poster.Poster; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; +import dev.caskeleton.sample.portfolio.domain.poster.PosterSortField; import java.util.UUID; /** @@ -24,27 +25,20 @@ public final class PosterPersistenceMapper { public static PosterEntity toEntity(Poster p) { // Carry the domain version so JPA tells a new row (null → insert) from a tracked one. return new PosterEntity( - toUuid(p.id()), - p.title(), - p.caption(), - p.imageAttachment() - instanceof dev.caskeleton.sample.portfolio.domain.poster.LegacyPosterImageAttachment - ? p.imageKey() - : null, - p.imageReference(), - p.status(), - p.version()); + toUuid(p.id()), p.title(), p.caption(), p.imageReference(), p.status(), p.version()); } public static Poster toDomain(PosterEntity e) { PosterId id = PosterId.of(e.getId().toString()); return Poster.rehydrate( - id, - e.getTitle(), - e.getCaption(), - e.getImageKey(), - e.getImageReference(), - e.getStatus(), - e.getVersion()); + id, e.getTitle(), e.getCaption(), e.getImageReference(), e.getStatus(), e.getVersion()); + } + + /** The entity property a logical sort field orders by. */ + public static String sortProperty(PosterSortField field) { + return switch (field) { + case TITLE -> "title"; + case STATUS -> "status"; + }; } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapper.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapper.java index 43f93472..6e08f19b 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapper.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/mapper/WorkLogPersistenceMapper.java @@ -5,6 +5,7 @@ import dev.caskeleton.sample.portfolio.domain.worklog.Period; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLog; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogId; import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogOwner; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; import java.util.UUID; public final class WorkLogPersistenceMapper { @@ -51,4 +52,12 @@ public final class WorkLogPersistenceMapper { new Period(e.getPeriodStart(), e.getPeriodEnd()), e.getVersion()); } + + /** The entity property a logical sort field orders by. */ + public static String sortProperty(WorkLogSortField field) { + return switch (field) { + case TITLE -> "title"; + case PERIOD_START -> "periodStart"; + }; + } } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageAttachmentCasRepository.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageAttachmentCasRepository.java index a80817de..ac79c69b 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageAttachmentCasRepository.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterImageAttachmentCasRepository.java @@ -9,7 +9,11 @@ import java.time.Instant; import java.util.List; import org.springframework.stereotype.Repository; -/** PostgreSQL conditional V8 attachment update that returns the exact replaced reference. */ +/** + * PostgreSQL conditional V8 attachment update that returns the exact replaced reference. It also + * clears a pre-V8 {@code image_key}, so a poster written by the removed legacy upload mode takes a + * canonical image through this path instead of being stuck behind the single-locator constraint. + */ @Repository public class PosterImageAttachmentCasRepository implements PosterImageAttachmentCompareAndSetPort { @@ -20,12 +24,12 @@ public class PosterImageAttachmentCasRepository implements PosterImageAttachment FROM poster WHERE id = :posterId AND version = :expectedVersion - AND image_key IS NULL FOR UPDATE ), updated AS ( UPDATE poster AS poster SET image_reference = :reference, + image_key = NULL, updated_at = :updatedAt, updated_by = :updatedBy, version = poster.version + 1 diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java index b4b6bdbb..281b3857 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java @@ -70,7 +70,9 @@ public class PosterRepositoryAdapter implements PosterRepository { Sort sort = sortField == null ? Sort.unsorted() - : Sort.by(ascending ? Sort.Direction.ASC : Sort.Direction.DESC, sortField.property()); + : Sort.by( + ascending ? Sort.Direction.ASC : Sort.Direction.DESC, + PosterPersistenceMapper.sortProperty(sortField)); PageRequest pageRequest = PageRequest.of(safePage, safeSize, sort); Page result = status == null ? jpa.findAll(pageRequest) : jpa.findByStatus(status, pageRequest); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java index 5d2e90ff..2e867330 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapter.java @@ -71,7 +71,9 @@ public class WorkLogRepositoryAdapter implements WorkLogRepository { Sort sort = sortField == null ? Sort.unsorted() - : Sort.by(ascending ? Sort.Direction.ASC : Sort.Direction.DESC, sortField.property()); + : Sort.by( + ascending ? Sort.Direction.ASC : Sort.Direction.DESC, + WorkLogPersistenceMapper.sortProperty(sortField)); PageRequest pageRequest = PageRequest.of(safePage, safeSize, sort); Page result = category == null ? jpa.findAll(pageRequest) : jpa.findByCategory(category, pageRequest); diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyV2.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyV2.java index 1225b146..c8cf4bdf 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyV2.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/event/PosterImageAttachmentReadyV2.java @@ -6,7 +6,7 @@ import dev.caskeleton.application.objectstorage.model.ObjectMediaType; import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; -/** New V2 ready event; the legacy image-attached/imageKey event remains unchanged. */ +/** V2 ready event emitted when a published image reference is attached. */ public record PosterImageAttachmentReadyV2( PosterId posterId, ObjectOperationId operationId, diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java index b1be845a..e2210e94 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/PublishPosterImageUseCase.java @@ -29,6 +29,7 @@ import dev.caskeleton.sample.portfolio.application.event.PosterImageAttachmentPr import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageOperationIdFactory; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationFingerprint; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationParameters; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationPolicy; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservation; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservationCodec; @@ -83,10 +84,7 @@ public class PublishPosterImageUseCase ObjectPublicationHandoffPort handoffs, PosterImagePublicationEventPublisher events, PosterImagePublicationPolicy policy, - ObjectDestinationId destination, - ObjectOperationEpoch epoch, - Duration intentTtl, - Duration handoffLease, + PosterImagePublicationParameters parameters, Clock clock) { this.intents = intents; this.sanitizedContexts = sanitizedContexts; @@ -97,10 +95,10 @@ public class PublishPosterImageUseCase this.handoffs = handoffs; this.events = events; this.policy = policy; - this.destination = destination; - this.epoch = epoch; - this.intentTtl = intentTtl; - this.handoffLease = handoffLease; + this.destination = parameters.destination(); + this.epoch = parameters.epoch(); + this.intentTtl = parameters.intentTtl(); + this.handoffLease = parameters.handoffLease(); this.clock = clock; } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/ReconcilePosterImageUploadUseCase.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/ReconcilePosterImageUploadUseCase.java index a5c0b0a5..1abcba7a 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/ReconcilePosterImageUploadUseCase.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/poster/ReconcilePosterImageUploadUseCase.java @@ -30,7 +30,16 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; import java.time.Clock; import java.time.Duration; -/** Worker boundary: finalize outside DB, then commit one deterministic READY/SUPERSEDED TX3. */ +/** + * Finalize outside DB, then commit one deterministic READY/SUPERSEDED TX3. + * + *

An explicit command, not a worker: the sample ships no scheduler that calls it (P14-new-3). An + * upload whose publish step crashed stays PENDING — or ABORT_AUTHORIZED, when an abort was + * authorized before storage accepted it — until someone sends this command for its poster and + * operation id. It accepts both states, so an adopter that adds a reconcile job must select both; + * {@code PosterImageUploadIntentStorePort#claimPending} claims PENDING only and is not that + * selector. + */ @RequiresPermission("poster:write") @UseCaseCapability( transactionMode = TransactionMode.WRITE, diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAttachmentCompareAndSetPort.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAttachmentCompareAndSetPort.java index 8942d0e0..76ea8833 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAttachmentCompareAndSetPort.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageAttachmentCompareAndSetPort.java @@ -4,7 +4,7 @@ import dev.caskeleton.sample.portfolio.domain.poster.PosterId; import dev.caskeleton.sample.portfolio.domain.poster.PosterImageReference; import java.time.Instant; -/** Atomic V8 canonical attachment write; legacy-key rows must be adopted first. */ +/** Atomic V8 canonical attachment write; it also clears a pre-V8 raw key on the same row. */ public interface PosterImageAttachmentCompareAndSetPort { Result attach( diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationParameters.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationParameters.java new file mode 100644 index 00000000..fbce59a2 --- /dev/null +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImagePublicationParameters.java @@ -0,0 +1,36 @@ +package dev.caskeleton.sample.portfolio.application.posterimage; + +import dev.caskeleton.application.objectstorage.identity.ObjectDestinationId; +import dev.caskeleton.application.objectstorage.identity.ObjectOperationEpoch; +import java.time.Duration; +import java.util.Objects; + +/** + * The deployment values a poster image publication runs with, as one value instead of four loose + * constructor arguments. + * + * @param destination the object storage destination poster images publish into + * @param epoch the operation epoch every operation key of this deployment carries + * @param intentTtl how long an upload intent may stay unfinished + * @param handoffLease how long a publish holds its storage handoff claim + */ +public record PosterImagePublicationParameters( + ObjectDestinationId destination, + ObjectOperationEpoch epoch, + Duration intentTtl, + Duration handoffLease) { + + public PosterImagePublicationParameters { + Objects.requireNonNull(destination, "destination"); + Objects.requireNonNull(epoch, "epoch"); + requirePositive(intentTtl, "intentTtl"); + requirePositive(handoffLease, "handoffLease"); + } + + private static void requirePositive(Duration value, String name) { + Objects.requireNonNull(value, name); + if (value.isZero() || value.isNegative()) { + throw new IllegalArgumentException(name + " must be positive"); + } + } +} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageUploadIntentStorePort.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageUploadIntentStorePort.java index d74d7672..5ce13b37 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageUploadIntentStorePort.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/posterimage/PosterImageUploadIntentStorePort.java @@ -21,6 +21,11 @@ public interface PosterImageUploadIntentStorePort { PosterImageUploadIntent compareAndSet(long expectedRevision, PosterImageUploadIntent replacement); + /** + * Claims one lapsed PENDING intent. No sample code calls it: reconciliation is the explicit + * {@code ReconcilePosterImageUploadUseCase} command, and a worker built on this method would miss + * ABORT_AUTHORIZED intents that the command also finishes. + */ Optional claimPending( String claimantDigest, Instant now, Duration leaseDuration); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageObjectStorageConfig.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageObjectStorageConfig.java index 95524c51..51d28a2c 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageObjectStorageConfig.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/objectstorage/PosterImageObjectStorageConfig.java @@ -16,6 +16,7 @@ import dev.caskeleton.sample.portfolio.application.poster.ReconcilePosterImageUp import dev.caskeleton.sample.portfolio.application.poster.RetirePosterImageUseCase; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageAttachmentCompareAndSetPort; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageOperationIdFactory; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationParameters; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationPolicy; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageRetirementIntentStorePort; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageSanitizedIdempotencyContextFactory; @@ -26,7 +27,7 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** Explicit canonical sample composition; absent from disabled and legacy-only profiles. */ +/** Explicit canonical sample composition; absent when the publication mode is off. */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(PosterImagePublicationSettings.class) @ConditionalOnProperty( @@ -64,10 +65,11 @@ public class PosterImageObjectStorageConfig { handoffs, events, policy, - ObjectDestinationId.of(settings.destination()), - ObjectOperationEpoch.of(settings.operationEpoch()), - settings.intentTtl(), - settings.handoffLease(), + new PosterImagePublicationParameters( + ObjectDestinationId.of(settings.destination()), + ObjectOperationEpoch.of(settings.operationEpoch()), + settings.intentTtl(), + settings.handoffLease()), clock); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/LegacyPosterImageAttachment.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/LegacyPosterImageAttachment.java deleted file mode 100644 index a819a0b4..00000000 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/LegacyPosterImageAttachment.java +++ /dev/null @@ -1,16 +0,0 @@ -package dev.caskeleton.sample.portfolio.domain.poster; - -/** Existing raw-key attachment retained only for the approved dual-read window. */ -public record LegacyPosterImageAttachment(String key) implements PosterImageAttachment { - - public LegacyPosterImageAttachment { - if (key == null || key.isBlank() || key.length() > 512) { - throw new IllegalArgumentException("legacy poster image key is invalid"); - } - } - - @Override - public String compatibilityValue() { - return key; - } -} diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/Poster.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/Poster.java index 9e14d56f..f03004d4 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/Poster.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/Poster.java @@ -9,10 +9,10 @@ import java.util.Objects; * invariant violations surface as {@link PosterInvariantException}. * *

The distinctive rule: a poster cannot be {@link #publish() published} until an image has been - * {@link #attachImage(String) attached} — this is what ties the object-storage upload to a domain - * invariant. The id is server-assigned (minted by a {@code PosterIdFactory} in the use case, never - * by the domain); {@code version} is {@code null} until the store persists it. Mirrors {@code - * WorkLog}. + * {@link #attachPublishedImage(PosterImageReference) attached} — this is what ties the + * object-storage publication to a domain invariant. The id is server-assigned (minted by a {@code + * PosterIdFactory} in the use case, never by the domain); {@code version} is {@code null} until the + * store persists it. Mirrors {@code WorkLog}. */ @AggregateRoot public class Poster { @@ -49,43 +49,22 @@ public class Poster { return new Poster(id, title, caption, null, PosterStatus.DRAFT, null); } - /** Rehydrates a persisted poster (no invariant re-derivation beyond construction checks). */ - public static Poster rehydrate( - PosterId id, - String title, - String caption, - String imageKey, - PosterStatus status, - Long version) { - return new Poster( - id, - title, - caption, - imageKey == null ? null : new LegacyPosterImageAttachment(imageKey), - status, - version); - } - /** - * Additive V8 dual read. Exactly one compatibility column may be populated; pending work never - * enters the aggregate. + * Rehydrates a persisted poster (no invariant re-derivation beyond construction checks). The only + * image locator is the publication-finalized opaque reference; the pre-V8 raw object key is no + * longer read because its dual-read window ended with the legacy upload mode. */ public static Poster rehydrate( PosterId id, String title, String caption, - String imageKey, String imageReference, PosterStatus status, Long version) { - if (imageKey != null && imageReference != null) { - throw new IllegalArgumentException( - "poster cannot contain both legacy key and published reference"); - } PosterImageAttachment attachment = - imageReference != null - ? new PublishedPosterImageAttachment(PosterImageReference.of(imageReference)) - : imageKey == null ? null : new LegacyPosterImageAttachment(imageKey); + imageReference == null + ? null + : new PublishedPosterImageAttachment(PosterImageReference.of(imageReference)); return new Poster(id, title, caption, attachment, status, version); } @@ -97,11 +76,6 @@ public class Poster { this.caption = newCaption == null ? "" : newCaption; } - /** Records the object-storage key of the uploaded image. */ - public void attachImage(String key) { - this.imageAttachment = new LegacyPosterImageAttachment(key); - } - /** Canonical V8 writer: only a publication-finalized opaque reference can be attached. */ public void attachPublishedImage(PosterImageReference reference) { this.imageAttachment = new PublishedPosterImageAttachment(reference); @@ -157,10 +131,6 @@ public class Poster { return caption; } - public String imageKey() { - return imageAttachment == null ? null : imageAttachment.compatibilityValue(); - } - public String imageReference() { return imageAttachment instanceof PublishedPosterImageAttachment published ? published.reference().value() diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttachment.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttachment.java index 3134d5ca..0374f735 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttachment.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterImageAttachment.java @@ -1,8 +1,7 @@ package dev.caskeleton.sample.portfolio.domain.poster; -/** Explicit compatibility-window image attachment; pending work never enters the aggregate. */ -public sealed interface PosterImageAttachment - permits LegacyPosterImageAttachment, PublishedPosterImageAttachment { +/** A poster's attached image; pending publication work never enters the aggregate. */ +public sealed interface PosterImageAttachment permits PublishedPosterImageAttachment { String compatibilityValue(); } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterSortField.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterSortField.java index b06ca6c9..a8978028 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterSortField.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/poster/PosterSortField.java @@ -1,32 +1,10 @@ package dev.caskeleton.sample.portfolio.domain.poster; /** - * Allow-listed sortable fields for the poster list endpoint. A closed enum (not an open string - * passed to the ORM) is what keeps the {@code ?sort=field,direction} contract safe. Mirrors {@code - * WorkLogSortField}. + * The logical fields a poster list may be ordered by. Mirrors {@code WorkLogSortField}: the wire + * names live in the web mapper and the sorted property in the persistence mapper. */ public enum PosterSortField { - TITLE("title"), - STATUS("status"); - - private final String property; - - PosterSortField(String property) { - this.property = property; - } - - /** Persistence property name this logical field maps to. */ - public String property() { - return property; - } - - /** Resolves a client-supplied sort field name, or {@code null} if not sortable. */ - public static PosterSortField fromRequest(String field) { - for (PosterSortField f : values()) { - if (f.property.equalsIgnoreCase(field)) { - return f; - } - } - return null; - } + TITLE, + STATUS } diff --git a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogSortField.java b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogSortField.java index f6b41a3c..f09c4f92 100644 --- a/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogSortField.java +++ b/src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/domain/worklog/WorkLogSortField.java @@ -1,31 +1,12 @@ package dev.caskeleton.sample.portfolio.domain.worklog; /** - * Allow-listed sortable fields for the WorkLog list endpoint. A closed enum (not an open string - * passed to the ORM) is what keeps the {@code ?sort=field,direction} contract safe. See README. + * The logical fields a WorkLog list may be ordered by. A closed enum (not an open string passed to + * the ORM) is what keeps the {@code ?sort=field,direction} contract safe. The wire names a client + * types live in the web mapper and the column each field sorts on lives in the persistence mapper; + * this enum names neither. See README. */ public enum WorkLogSortField { - TITLE("title"), - PERIOD_START("periodStart"); - - private final String property; - - WorkLogSortField(String property) { - this.property = property; - } - - /** Persistence property name this logical field maps to. */ - public String property() { - return property; - } - - /** Resolves a client-supplied sort field name, or {@code null} if not sortable. */ - public static WorkLogSortField fromRequest(String field) { - for (WorkLogSortField f : values()) { - if (f.property.equalsIgnoreCase(field)) { - return f; - } - } - return null; - } + TITLE, + PERIOD_START } diff --git a/src/sample-portfolio/src/main/resources/application.yml b/src/sample-portfolio/src/main/resources/application.yml index adeb5d4b..34bca6e5 100644 --- a/src/sample-portfolio/src/main/resources/application.yml +++ b/src/sample-portfolio/src/main/resources/application.yml @@ -246,6 +246,7 @@ ca-skeleton: app: poster-image: api: + # `publication` turns on the canonical upload endpoints; anything else leaves them off. mode: disabled idempotency: enabled: false diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java index e7abc430..cc39bd72 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/PosterControllerWireTest.java @@ -77,8 +77,11 @@ class PosterControllerWireTest { @MockitoBean GetPosterUseCase getUseCase; @MockitoBean ListPostersUseCase listUseCase; - private static Poster poster(String title, PosterStatus status, String imageKey) { - return Poster.rehydrate(PosterId.of(ID), title, "7월 한정", imageKey, status, 0L); + private static final String IMAGE_REFERENCE = + "osr1.0123456789ab.0123456789abcdefghjkmnpqrs.d53d9429ac"; + + private static Poster poster(String title, PosterStatus status, String imageReference) { + return Poster.rehydrate(PosterId.of(ID), title, "7월 한정", imageReference, status, 0L); } @Nested @@ -150,7 +153,7 @@ class PosterControllerWireTest { void getReturnsPoster() throws Exception { // given when(getUseCase.handle(any())) - .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, "posters/x/image")); + .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, IMAGE_REFERENCE)); // when ResultActions result = mvc.perform(get("/posters/" + ID)); @@ -160,7 +163,7 @@ class PosterControllerWireTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.data.id").value(ID)) .andExpect(jsonPath("$.data.status").value("PUBLISHED")) - .andExpect(jsonPath("$.data.imageKey").value("posters/x/image")); + .andExpect(jsonPath("$.data.imageKey").value(IMAGE_REFERENCE)); } @Test @@ -282,7 +285,7 @@ class PosterControllerWireTest { void publishReturnsPublishedPoster() throws Exception { // given when(publishUseCase.handle(any())) - .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, "posters/x/image")); + .thenReturn(poster("여름 세일", PosterStatus.PUBLISHED, IMAGE_REFERENCE)); // when ResultActions result = mvc.perform(post("/posters/" + ID + "/publish")); @@ -299,7 +302,7 @@ class PosterControllerWireTest { void archiveReturnsArchivedPoster() throws Exception { // given when(archiveUseCase.handle(any())) - .thenReturn(poster("여름 세일", PosterStatus.ARCHIVED, "posters/x/image")); + .thenReturn(poster("여름 세일", PosterStatus.ARCHIVED, IMAGE_REFERENCE)); // when ResultActions result = mvc.perform(post("/posters/" + ID + "/archive")); diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WebRequestParamsTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WebRequestParamsTest.java new file mode 100644 index 00000000..577c8108 --- /dev/null +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/controller/WebRequestParamsTest.java @@ -0,0 +1,51 @@ +package dev.caskeleton.sample.portfolio.adapter.inbound.web.controller; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; +import dev.caskeleton.sample.portfolio.adapter.inbound.web.mapper.WorkLogWebMapper; +import dev.caskeleton.sample.portfolio.domain.worklog.WorkLogSortField; +import java.util.Optional; +import org.junit.jupiter.api.Test; + +class WebRequestParamsTest { + + @Test + void aWireSortNameResolvesToItsLogicalFieldIgnoringCase() { + // when + Optional> sort = + WebRequestParams.sort("PERIODSTART,desc", WorkLogWebMapper.SORT_FIELDS); + + // then + assertThat(sort) + .get() + .extracting(WebRequestParams.Sort::field, WebRequestParams.Sort::ascending) + .containsExactly(WorkLogSortField.PERIOD_START, false); + } + + @Test + void aSortNameOutsideTheAllowListIsRefusedWithItsReasonCode() { + // when + Throwable thrown = + catchThrowable(() -> WebRequestParams.sort("owner,asc", WorkLogWebMapper.SORT_FIELDS)); + + // then + assertThat(thrown) + .isInstanceOfSatisfying( + PageValidationException.class, + e -> assertThat(e.reasonCode()).isEqualTo("SORT_FIELD_NOT_ALLOWED")) + .hasMessage("sort field 'owner' is not sortable"); + } + + @Test + void aBlankSortMeansUnsorted() { + assertThat(WebRequestParams.sort(" ", WorkLogWebMapper.SORT_FIELDS)).isEmpty(); + } + + @Test + void anUppercasePathIdIsNormalisedToTheCanonicalLowercaseUuid() { + assertThat(WebRequestParams.canonicalUuid("0190BD6E-7C3E-7ABC-8DEF-0123456789AB")) + .isEqualTo("0190bd6e-7c3e-7abc-8def-0123456789ab"); + } +} diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java index 303b8b11..634e9be5 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/DeletePosterImageRetirementTest.java @@ -86,8 +86,7 @@ class DeletePosterImageRetirementTest { private static PosterRepository postersHoldingAPublishedImage() { Poster poster = - Poster.rehydrate( - POSTER, "title", "caption", null, REFERENCE.value(), PosterStatus.DRAFT, 4L); + Poster.rehydrate(POSTER, "title", "caption", REFERENCE.value(), PosterStatus.DRAFT, 4L); PosterRepository posters = mock(PosterRepository.class); when(posters.findById(POSTER)).thenReturn(Optional.of(poster)); return posters; diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java index 21881d2b..7dc6c3b1 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImageAbortReconcileRaceTest.java @@ -58,6 +58,8 @@ import java.util.List; import java.util.Optional; import java.util.UUID; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Abort and reconcile of one upload intent: whichever finishes first wins (owner decision 22). @@ -122,6 +124,29 @@ class PosterImageAbortReconcileRaceTest { assertThat(intents.only().state()).isEqualTo(PosterImageUploadIntentState.READY); } + /** + * P14-new-3: the sample runs no reconcile worker, so the explicit reconcile command is the only + * way a parked intent is finished. It has to finish both non-terminal states a crashed publish + * can leave behind, not only PENDING. + */ + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void theReconcileCommandFinishesAPendingOrAbortAuthorizedIntent(boolean abortAuthorized) { + // given + intents.createOrRead(pendingWithLapsedClaim()); + if (abortAuthorized) { + authorizeAbortInTheDatabase(); + } + + // when + reconcile().handle(reconcileCommand()); + + // then + assertThat(List.of(intents.only().state(), attached)) + .containsExactly( + PosterImageUploadIntentState.READY, List.of(PosterImageReference.of(REFERENCE))); + } + @Test void anAbortThatArrivesAfterThePublicationIsAConflict() { // given diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java index 611fb922..1681338e 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/application/poster/PosterImagePublicationWorkflowTest.java @@ -36,6 +36,7 @@ import dev.caskeleton.sample.portfolio.application.command.PublishPosterImageCom import dev.caskeleton.sample.portfolio.application.event.PosterImagePublicationEventPublisher; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageIdempotencyScopeDigest; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageOperationIdFactory; +import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationParameters; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationPolicy; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImagePublicationReservation; import dev.caskeleton.sample.portfolio.application.posterimage.PosterImageSanitizedIdempotencyContextFactory; @@ -230,10 +231,11 @@ class PosterImagePublicationWorkflowTest { Optional::empty, CLOCK), new PosterImagePublicationPolicy(1024), - ObjectDestinationId.of("poster"), - ObjectOperationEpoch.of("poster-image-v1"), - Duration.ofHours(24), - Duration.ofMinutes(1), + new PosterImagePublicationParameters( + ObjectDestinationId.of("poster"), + ObjectOperationEpoch.of("poster-image-v1"), + Duration.ofHours(24), + Duration.ofMinutes(1)), CLOCK); } diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java index 432cf7b4..db55d545 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/bootstrap/security/SamplePublicAccessSecurityConfigTest.java @@ -6,12 +6,11 @@ import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import dev.caskeleton.adapter.inbound.web.auth.SecurityConfig; -import dev.caskeleton.adapter.inbound.web.authz.MethodSecurityConfig; import dev.caskeleton.adapter.inbound.web.config.JacksonNullableConfig; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration; import dev.caskeleton.sample.portfolio.SamplePortfolioApplication; import dev.caskeleton.sample.portfolio.adapter.inbound.web.controller.WorkLogController; import dev.caskeleton.sample.portfolio.adapter.inbound.web.error.DomainExceptionHandler; @@ -84,16 +83,24 @@ class SamplePublicAccessSecurityConfigTest { } @Test - void sampleCompositionRootDoesNotImportProductionJwtOrMethodSecurity() { + void sampleCompositionRootExcludesOnlyTheWebSecurityRoot() { + // when + EnableAutoConfiguration autoConfiguration = + AnnotationUtils.findAnnotation( + SamplePortfolioApplication.class, EnableAutoConfiguration.class); + + // then + assertThat(autoConfiguration.exclude()).containsExactly(WebSecurityAutoConfiguration.class); + } + + @Test + void sampleCompositionRootScansOnlyTheSamplePackage() { // when ComponentScan componentScan = AnnotationUtils.findAnnotation(SamplePortfolioApplication.class, ComponentScan.class); // then - assertThat(componentScan).isNotNull(); - assertThat(componentScan.excludeFilters()) - .flatExtracting(filter -> List.of(filter.classes())) - .contains(SecurityConfig.class, MethodSecurityConfig.class); + assertThat(componentScan.basePackages()).containsExactly("dev.caskeleton.sample"); } @Test @@ -129,8 +136,10 @@ class SamplePublicAccessSecurityConfigTest { DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, - // The production web root brings the JWT and method security this sample leaves out. - WebAdapterAutoConfiguration.class + // The web roots are imported piecewise below; the security root is the JWT and method + // security this sample leaves out. + WebAdapterAutoConfiguration.class, + WebSecurityAutoConfiguration.class }) @Import({ WorkLogController.class, diff --git a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java index 00d3b1a7..c543d72a 100644 --- a/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java +++ b/src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/domain/poster/PosterTest.java @@ -83,7 +83,7 @@ class PosterTest { void publishWithAnAttachedImageMovesToPublishedAndKeepsTheImage() { // given Poster poster = aDraft(); - poster.attachImage("posters/x/image"); + poster.attachPublishedImage(REFERENCE); // when poster.publish(); @@ -104,28 +104,8 @@ class PosterTest { // then assertThat(poster) - .extracting(Poster::imageAttachment, Poster::imageReference, Poster::imageKey) - .containsExactly( - new PublishedPosterImageAttachment(REFERENCE), REFERENCE.value(), REFERENCE.value()); - } - - @Test - void dualReadRejectsAmbiguousLegacyAndPublishedColumns() { - Throwable thrown = - catchThrowable( - () -> - Poster.rehydrate( - ID, - "title", - "caption", - "posters/legacy", - REFERENCE.value(), - PosterStatus.DRAFT, - 1L)); - - assertThat(thrown) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("poster cannot contain both legacy key and published reference"); + .extracting(Poster::imageAttachment, Poster::imageReference) + .containsExactly(new PublishedPosterImageAttachment(REFERENCE), REFERENCE.value()); } @Test @@ -144,7 +124,7 @@ class PosterTest { void archivedIsTerminalSoRepublishIsRejected() { // given Poster poster = aDraft(); - poster.attachImage("posters/x/image"); + poster.attachPublishedImage(REFERENCE); poster.publish(); poster.archive(); diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java index 6e1d3225..a811c52a 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/contract/OpenApiDriftContractTest.java @@ -7,6 +7,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.json.JsonMapper; import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration; import dev.caskeleton.sample.portfolio.adapter.inbound.web.controller.WorkLogController; import dev.caskeleton.sample.portfolio.application.worklog.BatchCreateWorkLogsUseCase; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase; @@ -164,12 +166,12 @@ class OpenApiDriftContractTest { ServletWebSecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class - }, - // The snapshot is the controller's surface; the web adapter's filters and security are - // not part of it and need collaborators this slice does not assemble. - excludeName = - "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") + HibernateJpaAutoConfiguration.class, + // The snapshot is the controller's surface; the web adapter's filters and security are + // not part of it and need collaborators this slice does not assemble. + WebAdapterAutoConfiguration.class, + WebSecurityAutoConfiguration.class + }) @Import({WorkLogController.class, OpenApiContractConfig.class}) static class OpenApiDriftTestApp {} } diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java index 587da00e..60b5fac6 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/date/DateHeaderContractTest.java @@ -3,6 +3,8 @@ package dev.caskeleton.sample.portfolio.adapter.inbound.web.date; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.util.StringUtils.hasText; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.springframework.beans.factory.annotation.Autowired; @@ -61,12 +63,12 @@ class DateHeaderContractTest { ServletWebSecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class - }, - // The Date header comes from Tomcat; the web adapter's filters and security need - // collaborators this probe app does not assemble. - excludeName = - "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") + HibernateJpaAutoConfiguration.class, + // The Date header comes from Tomcat; the web adapter's filters and security need + // collaborators this probe app does not assemble. + WebAdapterAutoConfiguration.class, + WebSecurityAutoConfiguration.class + }) static class DateProbeApp { @RestController diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java index 32fb177b..e0ae0fff 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/filter/VirtualThreadMdcE2ETest.java @@ -6,6 +6,8 @@ import dev.caskeleton.adapter.inbound.web.config.JacksonNullableConfig; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.error.GlobalExceptionHandler; 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.WebSecurityAutoConfiguration; import dev.caskeleton.application.observability.UserPrincipalPseudonymizerPort; import dev.caskeleton.sample.portfolio.adapter.inbound.web.error.DomainExceptionHandler; import java.net.URI; @@ -144,12 +146,12 @@ class VirtualThreadMdcE2ETest { OAuth2ResourceServerAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, - DataJpaRepositoriesAutoConfiguration.class - }, - // The filter under test is imported below with a stub pseudonymizer; the rest of the web - // adapter (its security answers 401) is not part of this pin. - excludeName = - "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") + DataJpaRepositoriesAutoConfiguration.class, + // The filter under test is imported below with a stub pseudonymizer; the rest of the web + // adapter (its security answers 401) is not part of this pin. + WebAdapterAutoConfiguration.class, + WebSecurityAutoConfiguration.class + }) @Import({ ContextProbeController.class, GlobalExceptionHandler.class, diff --git a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java index de308f4a..8b3d75ab 100644 --- a/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java +++ b/src/sample-portfolio/src/webSystemTest/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/openapi/OpenApiSnapshotTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatObject; import dev.caskeleton.adapter.inbound.web.config.OpenApiContractConfig; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration; +import dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebSecurityAutoConfiguration; import dev.caskeleton.sample.portfolio.adapter.inbound.web.controller.WorkLogController; import dev.caskeleton.sample.portfolio.application.worklog.BatchCreateWorkLogsUseCase; import dev.caskeleton.sample.portfolio.application.worklog.CreateWorkLogUseCase; @@ -95,12 +97,12 @@ class OpenApiSnapshotTest { ServletWebSecurityAutoConfiguration.class, OAuth2ResourceServerAutoConfiguration.class, DataSourceAutoConfiguration.class, - HibernateJpaAutoConfiguration.class - }, - // The api-docs describe the controller's surface; the web adapter's filters and security - // are not part of it and need collaborators this slice does not assemble. - excludeName = - "dev.caskeleton.adapter.inbound.web.mvc.autoconfigure.WebAdapterAutoConfiguration") + HibernateJpaAutoConfiguration.class, + // The api-docs describe the controller's surface; the web adapter's filters and security + // are not part of it and need collaborators this slice does not assemble. + WebAdapterAutoConfiguration.class, + WebSecurityAutoConfiguration.class + }) @Import({WorkLogController.class, OpenApiContractConfig.class}) static class OpenApiTestApp {} } diff --git a/src/shared-contract/CLAUDE.md b/src/shared-contract/CLAUDE.md index ed932bf1..1521fa95 100644 --- a/src/shared-contract/CLAUDE.md +++ b/src/shared-contract/CLAUDE.md @@ -21,12 +21,12 @@ envelope shape, metric cardinality bounds, tracing seam, domain-context propagat Korean, one message per `Category`, used by every transport). - Cross-cutting mapper sentinel (`error/MappingException`). - Request value contract (`request/Patch`). -- Framework-neutral Redis operational snapshot (`health/RedisHealthSnapshotProvider`) used by - adapters and bootstrap health composition without leaking Actuator or native client types. -- Tracing contract types (`tracing/TraceParent`, `tracing/BaggageAllowlist`, - `tracing/SpanErrorRecorder`) — W3C `traceparent` value type, baggage allowlist, - and the span-error-recording seam (feature-distributed-tracing-contract; the OTel +- Tracing contract types (`tracing/TraceParent`, `tracing/SpanErrorRecorder`) — W3C + `traceparent` value type and the span-error-recording seam (feature-distributed-tracing-contract; the OTel tracer runtime is a fork-activated seam, so these stay Java-stdlib-only). +- Registry-rule mirrors read only by contract tests live in `testFixtures`, not `main`: + `metrics/MetricNaming`, `metrics/CardinalityBounds`, `metrics/AlertSeverity`, + `tracing/BaggageAllowlist`. Move one to `main` only when production code consumes it. - Generic messaging envelope schema resources under `contracts/messaging/envelope/`. They own transport-neutral envelope metadata only; feature payload schemas remain in their feature-owner modules. Resource presence is not runtime discovery or registration. diff --git a/src/shared-contract/README.md b/src/shared-contract/README.md index c7ae1f42..125119e6 100644 --- a/src/shared-contract/README.md +++ b/src/shared-contract/README.md @@ -12,10 +12,6 @@ Micrometer·OTel 같은 프레임워크 타입을 import 하지 않는다. 그 persistence·outbound)이 프레임워크 충돌 없이 이 타입들을 공유할 수 있고, HTTP status 같은 전송 개념도 프레임워크 타입이 아니라 평범한 `int` 로 표현한다(매핑은 web 어댑터가 한다). -`health/RedisHealthSnapshotProvider`도 같은 원칙을 따른다. Redis adapter는 native client나 -예외를 노출하지 않고 bounded role/capability 상태만 제공하며, bootstrap이 이를 Actuator -health로 변환한다. - --- ## ratelimit — edge enforcement 계약 @@ -342,6 +338,11 @@ Spring/Lettuce 타입을 노출하지 않는다. > **프로젝트 선택** — 외부 표준에서 유도한 게 아니라 이 스켈레톤이 합의한 운영 가정이며, > 트래픽 패턴/SLO 데이터에 따라 개정 대상인 "문서화된 기본값"이다. 모든 클래스는 stdlib-only(Spring/ > Jackson/Micrometer 의존 없음). +> +> `MetricNaming`·`CardinalityBounds`·`AlertSeverity`(그리고 tracing 의 `BaggageAllowlist`)는 production +> 소비자가 없고 레지스트리 계약 테스트(app-bootstrap `MetricsAlertingContractTest`· +> `DistributedTracingContractTest`)만 읽으므로 `src/testFixtures` 에 있다. production 에 있는 것은 +> `ForbiddenMetricTags` 하나다(`MetricsCardinalityMeterFilter` 가 쓴다). ### MetricNaming - **Micrometer dot.case 메트릭 이름의 작명/단위 접미사 규칙**(D2/D3 + §3). @@ -451,19 +452,15 @@ Spring/Lettuce 타입을 노출하지 않는다. virtual-thread 와 `StructuredTaskScope.fork()` 경계 너머로 전파하는 계약이다. ### 설계 골격 — "Default + 교체 가능한 추상화" (rate-limit 패턴) -동작하는 기본 구현을 제공하되 strategy seam 뒤에 두어, 호출부를 건드리지 않고 교체/대체할 수 있게 한다. -`RateLimiter` / `RateLimitAlgorithm` / `RateLimiterFactory` 와 정확히 같은 구조다: +동작하는 기본 구현을 port 뒤에 두어, 호출부를 건드리지 않고 교체할 수 있게 한다: - **`DomainContextPropagator`** — port(인터페이스). - **`ThreadLocalDomainContextPropagator`** — 기본 구현(plain `ThreadLocal`, 명시적 capture/restore, virtual-thread 안전, `InheritableThreadLocal` 미사용). -- **`DomainContextStrategy`** — 선택 가능한 strategy enum(기본 `THREAD_LOCAL`; `MICROMETER`/ - `SCOPED_VALUE` 는 주석으로만 남긴 향후 strategy). -- **`DomainContextPropagatorFactory`** — 유일한 확장점(단일 `switch`). - **`DomainContextKey`** — 도메인이 공급하는 per-value 확장점(키), `RateLimitKeyResolver` 와 유사. -Spring 배선(`DomainContextSettings` + `DomainContextConfig`, `ca-skeleton.domain-context.strategy` -바인딩)은 `app-bootstrap` 에 있고, 설정이 없으면 strategy 는 `THREAD_LOCAL` 로 기본 동작한다. +Spring 배선(`DomainContextConfig`)은 `app-bootstrap` 에 있고 `ThreadLocalDomainContextPropagator` 를 +직접 만든다. 구현이 하나뿐이라 strategy enum·factory·선택 설정은 두지 않는다. ### 무엇을 일부러 ship 하지 않았나 (그리고 왜) - **도메인 키:** 스켈레톤엔 도메인이 없으므로 `DomainContextKey` 상수를 ship 하지 않고, 기본적으로 @@ -471,7 +468,7 @@ Spring 배선(`DomainContextSettings` + `DomainContextConfig`, `ca-skeleton.doma 없다 — route 가 없는 `RateLimitKeyResolver` 와 같다). - **`ScopedValue`/`StructuredTaskScope` strategy:** Java 21 preview API 이고 빌드에 `--enable-preview` 가 없어(빌드 사실 C1) 운영에서 컴파일되지 않는다. `domain_context_propagation_primitives_stay_unshipped` - ArchUnit 규칙(app-bootstrap `CleanArchitectureTest`)이, strategy seam 을 통해 활성화되기 전까지 + ArchUnit 규칙(app-bootstrap `ForbiddenApiArchitectureTest`)이, 해당 구현이 추가되기 전까지 이를 운영 코드에서 배제한다. ### 경계 → 메커니즘 위임 맵 (S1, 참고용) @@ -491,8 +488,7 @@ Spring 배선(`DomainContextSettings` + `DomainContextConfig`, `ca-skeleton.doma ### DomainContextPropagator (port) - 도메인/비즈니스 컨텍스트를 스레드·`fork()` 경계 너머 전파하는 **strategy seam**(S2/S3). 애플리케이션 - 코드는 이 인터페이스만 의존하고, Factory 가 설정에서 구체 strategy 를 고른다. strategy 추가 = "새 impl - + enum 값 1개 + factory case 1개", 호출부 변경 없음. + 코드는 이 인터페이스만 의존하고, 구현은 composition root 가 고른다. 구현 교체는 호출부 변경이 없다. - **진단(diagnostic) 컨텍스트는 여기 두지 않는다.** `request_id`/`trace_id`/`correlation_id` 는 MDC 에 살고 inbound 필터가 virtual thread 에서 전파한다(B6 + D11). 이 propagator 는 **도메인 채널** — 별개의 관심사다. @@ -500,23 +496,16 @@ Spring 배선(`DomainContextSettings` + `DomainContextConfig`, `ca-skeleton.doma `no_inheritable_thread_local` ArchUnit 규칙으로 금지). 스레드/`fork()` 경계를 넘는 코드는 `wrap()` 또는 `capture()`+`restore()` 로 컨텍스트를 명시적으로 재확립한다. -### DomainContextStrategy (enum) -- `THREAD_LOCAL` 이 기본이자 현재 ship 된 유일한 값이다. 값을 추가하려면 enum 값 + `DomainContextPropagator` - 구현 + Factory case 를 함께 더한다(`RateLimitAlgorithm` 패턴). -- **`THREAD_LOCAL`:** plain `ThreadLocal` + 명시적 capture/restore. virtual-thread 안전(VT 마다 자기 - copy), `no_inheritable_thread_local` 금지 준수(`InheritableThreadLocal` 아님), 추가 의존성 0. -- **향후 strategy(주석으로만 존재):** - - `MICROMETER` — `io.micrometer:context-propagation` 의 `ContextSnapshot`/`ContextRegistry`. 안정적 - API 이고 MDC/tracing 과 같은 채널에 통합된다. 다중 키나 Reactor bridge 가 필요할 때 고른다 - (C7: 활성화 전에 virtual-thread 동작을 확인할 것). - - `SCOPED_VALUE` — Java 21 `ScopedValue`. 불변이며 `StructuredTaskScope` 안에서 자동 상속된다. - PREVIEW: `--enable-preview` 가 필요한데 현재 빌드는 켜지 않는다(C1) → +### 전략이 하나뿐인 이유 +- 현재 구현은 `ThreadLocalDomainContextPropagator` 하나이고 app-bootstrap `DomainContextConfig` 가 직접 + 만든다. 경우가 하나뿐인 strategy enum·factory·설정 키는 지웠다(A-10c). 두 번째 구현이 필요해지면 + 그 구현과 선택 설정을 함께 추가한다. +- **후보(코드 없음):** + - `io.micrometer:context-propagation` 의 `ContextSnapshot`/`ContextRegistry`. 다중 키나 Reactor + bridge 가 필요할 때 고른다(C7: 활성화 전에 virtual-thread 동작을 확인할 것). + - Java 21 `ScopedValue`. PREVIEW 라 `--enable-preview` 가 필요한데 현재 빌드는 켜지 않는다(C1) → `domain_context_propagation_primitives_stay_unshipped` ArchUnit 규칙으로 guard 된다. -### DomainContextPropagatorFactory -- 설정된 strategy 를 만들어 주는 곳(S2). 내부의 단일 `switch` 가 유일한 확장점이다 — strategy 추가 = - enum 값 + 구현 + case, 호출부는 그대로. `RateLimiterFactory` 와 같은 모양. - ### ThreadLocalDomainContextPropagator (기본 구현) - plain `ThreadLocal` 이 현재 스레드의 도메인 컨텍스트 맵을 들고, 스레드 경계는 명시적 capture/restore 로 넘긴다(D4/D6). @@ -524,7 +513,7 @@ Spring 배선(`DomainContextSettings` + `DomainContextConfig`, `ca-skeleton.doma 조용히 새지 않고 `no_inheritable_thread_local` ArchUnit 규칙(B6)을 지킨다. virtual thread 는 각자 자기 copy 를 갖는다(Oracle Java 21 docs, TL-VT-C1) → 같은 스레드 read 는 동작하지만 fork 시 상속은 없다 — 그래서 핸드오프가 `wrap()`/`capture()` 로 **명시적**이어야 하는 것이다. -- multi-key 고빈도 변경이나 Reactor bridging 용이 아니다 — 그건 `MICROMETER` strategy 의 일이다. 이 +- multi-key 고빈도 변경이나 Reactor bridging 용이 아니다 — 그건 context-propagation 기반 구현의 일이다. 이 기본 구현은 흔한 경우(작은 비즈니스 식별자 집합을 명시적 async 핸드오프 너머 운반)를 노린다. ### DomainContextKey diff --git a/src/shared-contract/build.gradle b/src/shared-contract/build.gradle index 66e2450e..7c82217b 100644 --- a/src/shared-contract/build.gradle +++ b/src/shared-contract/build.gradle @@ -1,8 +1,11 @@ plugins { id 'ca.java-library' + id 'java-test-fixtures' } // Skeleton-wide operational contracts only. No business/domain concepts. +// testFixtures holds the registry-rule mirrors (metric naming, cardinality bounds, alert severity, +// baggage allowlist) that only contract tests read; production code has no consumer for them. dependencies { } diff --git a/src/shared-contract/gradle.lockfile b/src/shared-contract/gradle.lockfile index 52406714..83f528ca 100644 --- a/src/shared-contract/gradle.lockfile +++ b/src/shared-contract/gradle.lockfile @@ -1,38 +1,38 @@ # This is a Gradle generated file for dependency locking. # Manual edits can break the build and are not advised. # This file is expected to be part of source control. -com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor +com.github.ben-manes.caffeine:caffeine:3.2.4=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.github.kevinstern:software-and-algorithms:1.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.github.spotbugs:spotbugs-annotations:4.10.2=spotbugs com.github.spotbugs:spotbugs:4.10.2=spotbugs com.github.stephenc.jcip:jcip-annotations:1.0-1=spotbugs -com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.auto:auto-common:1.2.2=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor +com.google.auto.service:auto-service-annotations:1.0.1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto.value:auto-value-annotations:1.9=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.auto:auto-common:1.2.2=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.code.findbugs:jsr305:3.0.2=checkstyle,spotbugs com.google.code.gson:gson:2.13.2=spotbugs -com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotation:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.errorprone:error_prone_annotations:2.41.0=spotbugs com.google.errorprone:error_prone_annotations:2.47.0=checkstyle -com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.guava:guava:33.5.0-jre=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor +com.google.errorprone:error_prone_annotations:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_check_api:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.errorprone:error_prone_core:2.49.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.googlejavaformat:google-java-format:1.35.0=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:failureaccess:1.0.3=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.guava:guava:33.5.0-jre=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.google.guava:guava:33.6.0-jre=checkstyle -com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor +com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.j2objc:j2objc-annotations:3.1=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +com.google.protobuf:protobuf-java:4.33.2=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor com.h3xstream.findsecbugs:findsecbugs-plugin:1.14.0=spotbugsPlugins com.puppycrawl.tools:checkstyle:13.5.0=checkstyle commons-beanutils:commons-beanutils:1.11.0=checkstyle commons-collections:commons-collections:3.2.2=checkstyle commons-io:commons-io:2.21.0=spotbugs info.picocli:picocli:4.7.7=checkstyle -io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor -javax.inject:javax.inject:1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor +io.github.eisop:dataflow-errorprone:3.41.0-eisop1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +io.github.java-diff-utils:java-diff-utils:4.12=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor +javax.inject:javax.inject:1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor jaxen:jaxen:2.0.6=spotbugs net.bytebuddy:byte-buddy:1.17.8=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath net.sf.saxon:Saxon-HE:12.9=checkstyle,spotbugs @@ -58,7 +58,7 @@ org.codehaus.plexus:plexus-container-default:2.1.0=checkstyle org.codehaus.plexus:plexus-utils:3.3.0=checkstyle org.dom4j:dom4j:2.2.0=spotbugs org.javassist:javassist:3.28.0-GA=checkstyle -org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,edgeRateLimitContractTestCompileClasspath,testAnnotationProcessor,testCompileClasspath +org.jspecify:jspecify:1.0.1=annotationProcessor,checkstyle,edgeRateLimitContractTestAnnotationProcessor,edgeRateLimitContractTestCompileClasspath,testAnnotationProcessor,testCompileClasspath,testFixturesAnnotationProcessor org.junit.jupiter:junit-jupiter-api:6.0.3=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-engine:6.0.3=edgeRateLimitContractTestRuntimeClasspath,testRuntimeClasspath org.junit.jupiter:junit-jupiter-params:6.0.3=edgeRateLimitContractTestCompileClasspath,edgeRateLimitContractTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath @@ -75,10 +75,10 @@ org.ow2.asm:asm-commons:9.10.1=spotbugs org.ow2.asm:asm-tree:9.10.1=spotbugs org.ow2.asm:asm-util:9.10.1=spotbugs org.ow2.asm:asm:9.10.1=spotbugs -org.pcollections:pcollections:4.0.1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor +org.pcollections:pcollections:4.0.1=annotationProcessor,edgeRateLimitContractTestAnnotationProcessor,testAnnotationProcessor,testFixturesAnnotationProcessor org.reflections:reflections:0.10.2=checkstyle org.slf4j:slf4j-api:2.0.18=spotbugs,spotbugsSlf4j org.slf4j:slf4j-simple:2.0.17=spotbugsSlf4j org.slf4j:slf4j-simple:2.0.18=checkstyle org.xmlresolver:xmlresolver:5.3.3=checkstyle,spotbugs -empty=compileClasspath,runtimeClasspath +empty=compileClasspath,runtimeClasspath,testFixturesCompileClasspath,testFixturesRuntimeClasspath diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextPropagator.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextPropagator.java index 6bedf7bd..0605495c 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextPropagator.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextPropagator.java @@ -5,8 +5,8 @@ import java.util.concurrent.Callable; /** * Propagates domain / business-scoped context across thread and {@code StructuredTaskScope.fork()} - * boundaries. This is the strategy seam: application code depends only on this interface, and - * {@link DomainContextPropagatorFactory} picks the concrete strategy from configuration. + * boundaries. Application code depends only on this interface; the composition root picks the + * implementation. * *

This is the domain channel only — diagnostic context ({@code request_id}/{@code * trace_id}/{@code correlation_id}) lives in MDC, a separate concern. Hand-off across threads must @@ -14,8 +14,8 @@ import java.util.concurrent.Callable; * no_inheritable_thread_local} ArchUnit rule) via {@link #wrap(Runnable)} / {@link #wrap(Callable)} * or {@link #capture()} + {@link DomainContextSnapshot#restore()}. * - *

See the module README for the rate-limit-style seam rationale and how the {@code @Async} - * {@code TaskDecorator} is expected to use {@link #wrap(Runnable)}. + *

See the module README for how the {@code @Async} {@code TaskDecorator} is expected to use + * {@link #wrap(Runnable)}. */ public interface DomainContextPropagator { diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextPropagatorFactory.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextPropagatorFactory.java deleted file mode 100644 index 89db0310..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextPropagatorFactory.java +++ /dev/null @@ -1,19 +0,0 @@ -package dev.caskeleton.shared.concurrency; - -/** - * Builds the configured {@link DomainContextPropagator} strategy. The single {@code switch} below - * is the one extension point: a new strategy adds a {@link DomainContextStrategy} value, a {@link - * DomainContextPropagator} implementation, and a case here — nothing at the call sites changes. - * - *

See the module README (mirrors the {@code RateLimiterFactory} pattern). - */ -public final class DomainContextPropagatorFactory { - - private DomainContextPropagatorFactory() {} - - public static DomainContextPropagator create(DomainContextStrategy strategy) { - return switch (strategy) { - case THREAD_LOCAL -> new ThreadLocalDomainContextPropagator(); - }; - } -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextStrategy.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextStrategy.java deleted file mode 100644 index c154d317..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/DomainContextStrategy.java +++ /dev/null @@ -1,20 +0,0 @@ -package dev.caskeleton.shared.concurrency; - -/** - * Selectable domain-context propagation strategy, bound from {@code - * ca-skeleton.domain-context.strategy}. {@link #THREAD_LOCAL} is the shipped default; add a value - * here together with its {@link DomainContextPropagator} implementation and a {@link - * DomainContextPropagatorFactory} case to introduce a new strategy. - * - *

See the module README for the {@code MICROMETER} / {@code SCOPED_VALUE} strategies reserved - * for the future and why they are not shipped yet. - */ -public enum DomainContextStrategy { - - /** - * Plain {@code ThreadLocal} with explicit capture/restore — the default. Virtual-thread safe - * (per-virtual-thread copy), respects the {@code no_inheritable_thread_local} ban, and adds zero - * dependencies. - */ - THREAD_LOCAL -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java index b4718dd9..24d8b596 100644 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java +++ b/src/shared-contract/src/main/java/dev/caskeleton/shared/concurrency/package-info.java @@ -1,17 +1,14 @@ /** * Runtime context propagation contract — propagates domain / business context (e.g. a business - * identifier) across virtual-thread and {@code StructuredTaskScope.fork()} boundaries, behind a - * swappable strategy seam. + * identifier) across virtual-thread and {@code StructuredTaskScope.fork()} boundaries. * - *

The package ships a working default ({@code THREAD_LOCAL}) behind the {@link - * dev.caskeleton.shared.concurrency.DomainContextPropagator} port; the Spring wiring ({@code - * DomainContextSettings} + {@code DomainContextConfig}, bound from {@code - * ca-skeleton.domain-context.strategy}) lives in {@code app-bootstrap} and defaults to {@code - * THREAD_LOCAL} when unconfigured. + *

The package ships one implementation ({@link + * dev.caskeleton.shared.concurrency.ThreadLocalDomainContextPropagator}) behind the {@link + * dev.caskeleton.shared.concurrency.DomainContextPropagator} port; {@code app-bootstrap}'s {@code + * DomainContextConfig} constructs it directly. * - *

See the module README for the full design: the rate-limit-style seam, what stays unshipped - * (domain keys, the {@code ScopedValue} strategy) and why, and the boundary → mechanism - * delegation map. + *

See the module README for the full design: what stays unshipped (domain keys, the {@code + * ScopedValue} strategy) and why, and the boundary → mechanism delegation map. * * @see dev.caskeleton.shared */ diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/health/RedisHealthSnapshotProvider.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/health/RedisHealthSnapshotProvider.java deleted file mode 100644 index d43fcff0..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/health/RedisHealthSnapshotProvider.java +++ /dev/null @@ -1,103 +0,0 @@ -package dev.caskeleton.shared.health; - -import java.time.Instant; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -/** - * Framework-neutral operational snapshot for canonically bound Redis roles. - * - *

The Redis adapter implements this contract; the bootstrap composition root maps it to its - * health framework. No command client, native connection, credential, or secret material crosses - * this boundary. - */ -public interface RedisHealthSnapshotProvider { - - Snapshot snapshot(); - - record Snapshot(Instant observedAt, List roles) { - - public Snapshot { - Objects.requireNonNull(observedAt, "observedAt must be non-null"); - roles = List.copyOf(Objects.requireNonNull(roles, "roles must be non-null")); - } - } - - record RoleHealth( - Role role, - String deploymentId, - boolean required, - EvictionPolicy expectedEviction, - EvictionAttestation evictionAttestation, - Set capabilities, - State state, - Reason reason, - Instant semanticObservedAt, - long semanticAgeMillis, - boolean semanticStale) { - - public RoleHealth { - Objects.requireNonNull(role, "role must be non-null"); - Objects.requireNonNull(deploymentId, "deploymentId must be non-null"); - Objects.requireNonNull(expectedEviction, "expectedEviction must be non-null"); - Objects.requireNonNull(evictionAttestation, "evictionAttestation must be non-null"); - capabilities = - Set.copyOf(Objects.requireNonNull(capabilities, "capabilities must be non-null")); - Objects.requireNonNull(state, "state must be non-null"); - Objects.requireNonNull(reason, "reason must be non-null"); - Objects.requireNonNull(semanticObservedAt, "semanticObservedAt must be non-null"); - if (semanticAgeMillis < 0) { - throw new IllegalArgumentException("semanticAgeMillis must be non-negative"); - } - } - } - - enum Role { - CACHE, - COORDINATION, - SESSION - } - - enum Capability { - CACHE, - RATE_LIMIT, - IDEMPOTENCY, - EFFICIENCY_LEASE, - SESSION - } - - enum State { - AVAILABLE, - UNAVAILABLE, - OVERLOADED - } - - enum Reason { - COMMAND_UNAVAILABLE, - ROUTE_CLOSED, - SEMANTIC_PROBE_SUCCEEDED, - SEMANTIC_READ_WRITE_FAILED, - SEMANTIC_PROGRAM_ACL_DENIED, - SEMANTIC_PROGRAM_FAILED, - SERVER_VERSION_UNSUPPORTED, - SEMANTIC_PROBE_IN_PROGRESS, - SEMANTIC_OBSERVATION_STALE, - COMMAND_SATURATED, - RECENT_COMMAND_FAILURE - } - - enum EvictionPolicy { - ALLKEYS_LFU, - ALLKEYS_LRU, - NOEVICTION - } - - /** - * The runtime never requests Redis CONFIG access. The configured expectation therefore needs an - * external conformance check against the server's effective maxmemory-policy. - */ - enum EvictionAttestation { - CONFIGURED_EXPECTATION_ONLY - } -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecord.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecord.java deleted file mode 100644 index 18fc5eab..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecord.java +++ /dev/null @@ -1,42 +0,0 @@ -package dev.caskeleton.shared.opstore; - -import java.util.Objects; - -/** - * One durable operational record: an opaque value under a namespaced key, with a version. - * - *

Text rather than bytes, so the record has value equality and no defensive copying: a record - * holding a {@code byte[]} compares by array identity, which makes two equal records unequal and - * every {@code contains} check wrong. The namespace owner decides the encoding. - * - *

Opaque on purpose. The store must not know what a GraphQL persisted operation, a feature flag - * or a schema pin looks like, because the moment it does, every adapter that wants durable - * operational state has to negotiate its shape with a module that has nothing to do with it. - * - *

The version is the whole reason this is a record rather than a map entry. Operational state is - * written by admin planes and by more than one instance at once; without a compare-and-set token, - * "block this operation" and "approve this operation" issued a second apart resolve by arrival - * order rather than by intent, and the loser leaves no trace. - * - * @param namespace bounded owner of the key space, e.g. the capability that owns these records - * @param key identity within the namespace - * @param value the opaque payload, encoded by whoever owns the namespace - * @param version the value's version; {@link #ABSENT_VERSION} means the key holds nothing yet - */ -public record OperationalRecord(String namespace, String key, String value, long version) { - - /** The version a key holds before anything has been written to it. */ - public static final long ABSENT_VERSION = 0L; - - public OperationalRecord { - Objects.requireNonNull(namespace, "namespace is required"); - Objects.requireNonNull(key, "key is required"); - Objects.requireNonNull(value, "value is required"); - if (namespace.isBlank() || key.isBlank()) { - throw new IllegalArgumentException("operational record namespace and key are required"); - } - if (version < ABSENT_VERSION) { - throw new IllegalArgumentException("operational record version cannot be negative"); - } - } -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecordConflictException.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecordConflictException.java deleted file mode 100644 index a644f40b..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecordConflictException.java +++ /dev/null @@ -1,37 +0,0 @@ -package dev.caskeleton.shared.opstore; - -/** - * A compare-and-set lost: the stored version was not the one the caller read. - * - *

An exception rather than a boolean, because the caller who ignores a returned {@code false} is - * exactly the caller whose admin action silently did not happen. - */ -public final class OperationalRecordConflictException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - /** The stable code operators and clients match on. */ - public static final String CODE = "OPERATIONAL_RECORD_CONFLICT"; - - /** - * Creates the exception. - * - * @param namespace bounded owner of the key space - * @param key identity within the namespace - * @param expectedVersion the version the caller read - * @param actualVersion the version the store holds - */ - public OperationalRecordConflictException( - String namespace, String key, long expectedVersion, long actualVersion) { - super( - CODE - + ": " - + namespace - + "/" - + key - + " expected version " - + expectedVersion - + " but found " - + actualVersion); - } -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecordStorePort.java b/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecordStorePort.java deleted file mode 100644 index 8ceccfb0..00000000 --- a/src/shared-contract/src/main/java/dev/caskeleton/shared/opstore/OperationalRecordStorePort.java +++ /dev/null @@ -1,49 +0,0 @@ -package dev.caskeleton.shared.opstore; - -import java.util.Optional; - -/** - * Provider-neutral durable storage for operational records. - * - *

Owned here rather than by whichever adapter happens to need it first. An adapter that declares - * its own storage interface makes every durable implementation depend on that adapter: a Postgres - * or Redis outbound adapter implementing an inbound transport's interface points the dependency - * from infrastructure back at a transport boundary, which is the direction this repository's - * architecture exists to prevent. A neutral contract lets both sides depend on the contract and on - * nothing else. - * - *

Writes are compare-and-set because operational state has more than one writer. The expected - * version is the caller's evidence about what they read; a store that accepted a blind write would - * make a lost admin action indistinguishable from an applied one. - */ -public interface OperationalRecordStorePort { - - /** - * Reads a record. - * - * @param namespace bounded owner of the key space - * @param key identity within the namespace - */ - Optional find(String namespace, String key); - - /** - * Writes a record if its stored version is still the expected one. - * - * @param record the record to write, carrying the value to store - * @param expectedVersion the version the caller read, or {@link OperationalRecord#ABSENT_VERSION} - * to require that the key holds nothing - * @return the stored record with its new version - * @throws OperationalRecordConflictException when the stored version differs - */ - OperationalRecord compareAndSet(OperationalRecord record, long expectedVersion); - - /** - * Removes a record if its stored version is still the expected one. - * - * @param namespace bounded owner of the key space - * @param key identity within the namespace - * @param expectedVersion the version the caller read - * @throws OperationalRecordConflictException when the stored version differs - */ - void compareAndRemove(String namespace, String key, long expectedVersion); -} diff --git a/src/shared-contract/src/test/java/dev/caskeleton/shared/concurrency/DomainContextPropagatorFactoryTest.java b/src/shared-contract/src/test/java/dev/caskeleton/shared/concurrency/DomainContextPropagatorFactoryTest.java deleted file mode 100644 index d0fc3c9f..00000000 --- a/src/shared-contract/src/test/java/dev/caskeleton/shared/concurrency/DomainContextPropagatorFactoryTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package dev.caskeleton.shared.concurrency; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -/** The factory returns the default strategy's implementation (S2 swap seam). */ -class DomainContextPropagatorFactoryTest { - - @Test - void threadLocalStrategyYieldsTheThreadLocalPropagator() { - DomainContextPropagator propagator = - DomainContextPropagatorFactory.create(DomainContextStrategy.THREAD_LOCAL); - - assertThat(propagator).isInstanceOf(ThreadLocalDomainContextPropagator.class); - } - - @Test - void everyStrategyValueIsConstructible() { - // Guards the factory switch against a new enum value without a case (compile + - // runtime). Today THREAD_LOCAL is the only shipped strategy. - for (DomainContextStrategy strategy : DomainContextStrategy.values()) { - assertThat(DomainContextPropagatorFactory.create(strategy)).isNotNull(); - } - } -} diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/metrics/AlertSeverity.java b/src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/metrics/AlertSeverity.java similarity index 100% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/metrics/AlertSeverity.java rename to src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/metrics/AlertSeverity.java diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/metrics/CardinalityBounds.java b/src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/metrics/CardinalityBounds.java similarity index 100% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/metrics/CardinalityBounds.java rename to src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/metrics/CardinalityBounds.java diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/metrics/MetricNaming.java b/src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/metrics/MetricNaming.java similarity index 100% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/metrics/MetricNaming.java rename to src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/metrics/MetricNaming.java diff --git a/src/shared-contract/src/main/java/dev/caskeleton/shared/tracing/BaggageAllowlist.java b/src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/tracing/BaggageAllowlist.java similarity index 100% rename from src/shared-contract/src/main/java/dev/caskeleton/shared/tracing/BaggageAllowlist.java rename to src/shared-contract/src/testFixtures/java/dev/caskeleton/shared/tracing/BaggageAllowlist.java